目录
Java的枚举是一个特殊的类,一般表示一组常量。类似于26个字母、月份这种有几种固定的取值时,可以将其定义为枚举类型。
定义形式:
修饰符 enum 枚举类:基础类型{
枚举成员1,枚举成员2
}
- public enum MyEnum {
- Math,English,Chinese
- }
注意事项
补充:
- public enum MyEnum {
- Math,English,Chinese;
-
- public static void main(String[] args) {
- MyEnum myEnum = MyEnum.Math;
- switch (myEnum){
- case Math:
- System.out.println("math");
- break;
- case Chinese:
- System.out.println("Chinese");
- break;
- case English:
- System.out.println("english");
- break;
- }
- }
- }
| 方法 | 用途 |
| values() | 以数组形式返回枚举类型的所有成员 |
| ordinal() | 获取枚举成员的索引位置 |
| valueOf() | 将普通字符串转换为枚举实例 |
| compareTo() | 比较两个枚举成员在定义时的顺序 |
- public enum MyEnum {
- Math,English,Chinese;
-
- public static void main(String[] args) {
- MyEnum[] myEnums = MyEnum.values();
- for (int i = 0; i < myEnums.length; i++) {
- System.out.println(myEnums[i] +"下标是:"+ myEnums[i].ordinal());
- }
- }
- }

- public enum MyEnum {
- Math,English,Chinese;
-
- public static void main(String[] args) {
- System.out.println(Math.compareTo(English)); // -1
- System.out.println(Math.compareTo(Chinese)); // -2
- }
- }
- public enum MyEnum {
- Math,English,Chinese;
-
- public static void main(String[] args) {
- System.out.println(MyEnum.valueOf("Math"));
- System.out.println(MyEnum.valueOf("Math1"));
- }
- }

- public enum MyEnum {
- Math("Math",1),English("English",2),Chinese("Chinese",3);
- private String name;
- private int key;
-
- /**
- * 当枚举对象有参数后,需要提供相应的构造函数
- * 枚举的构造函数默认是私有的
- * @param name
- * @param key
- */
- private MyEnum(String name,int key){
- this.name = name;
- this.key = key;
- }
-
- public static void main(String[] args) {
- try {
- Class> c1 = Class.forName("demo2.MyEnum");
- Constructor> constructor = c1.getDeclaredConstructor(String.class,int.class);
- constructor.setAccessible(true);
- MyEnum myEnum = (MyEnum)constructor.newInstance("Java",12);
- System.out.println(myEnum);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.printStackTrace();
- }
- }
- }

报异常:没有对应的构造方法
原因:自定义的枚举类,都是默认继承java.lang.Enum。因此,需要帮助父类进行构造。
解决方案1:适用super 不可行
解决方案2:枚举的构造函数虽然我们只写了两个,但是默认还添加了两个,因此一共有四个。默认添加的参数通过源码可以看到:

- Constructor> constructor = c1.getDeclaredConstructor(String.class,int.class,String.class,int.class);
- constructor.setAccessible(true);
- MyEnum myEnum = (MyEnum)constructor.newInstance("Java",12,"父类的参数",1);
- System.out.println(myEnum);

原因:

- public enum TestEnum {
- INSTANCE;
- public TestEnum getInstance(){
- return INSTANCE;
- }
-
- public static void main(String[] args) {
- TestEnum testEnum1 = INSTANCE.getInstance();
- TestEnum testEnum2 = INSTANCE.getInstance();
- System.out.println(testEnum1 == testEnum2); // true
- }
- }