java基础(四) — 枚举 二、常见方法 三、进阶用法 四、辅助类

Enum实际上是一种特殊的类,编译后会转换成正常的类,如下简单定义一个枚举类

1
2
3
public enum Color {
WHITE,BLACK
}

经过编译后就会转换成一下的样子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

final class extends Enum
{
//前面定义的2种枚举实例
public static final Color WHITE;
public static final Color BLACK;

private static final Color $VALUES[];

static
{
//实例化枚举实例
WHITE = new Color("WHITE", 0);
BLACK = new Color("BLACK", 1);

$VALUES = (new Color[] {
WHITE, BLACK
});
}
//编译器为我们添加的静态的values()方法
public static Color[] values()
{
return (Color[])$VALUES.clone();
}
//编译器为我们添加的静态的valueOf()方法,注意间接调用了Enum类的valueOf方法
public static Color valueOf(String s)
{
return (Color)Enum.valueOf(Color, s);
}
//私有构造函数
private (String s, int i)
{
super(s, i);
}

}

二、常见方法

返回类型 方法名称 方法说明
int compareTo(E o) 比较此枚举与指定对象的顺序
boolean equals(Object other) 当指定对象等于此枚举常量时,返回 true。
Class<?> getDeclaringClass() 返回与此枚举常量的枚举类型相对应的 Class 对象
String name() 返回此枚举常量的名称,在其枚举声明中对其进行声明
int ordinal() 返回枚举常量的序数(它在枚举声明中的位置,其中初始常量序数为零)
String toString() 返回枚举常量的名称,它包含在声明中
static<T extends Enum> T static valueOf(Class enumType, String name) 返回带指定名称的指定枚举类型的枚举常量

值得注意的是Enum类内部会有一个构造函数,该构造函数只能有编译器调用,我们是无法手动操作的

三、进阶用法

1、结合抽象方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public enum Color {
WHITE{

public String getDesc() {
return "我是白色";
}
},BLACK {

public String getDesc() {
return "我是黑色";
}
};
public abstract String getDesc();
}

public class Main {
public static void main(String argr[]){
String color = Color.WHITE.getDesc();
}
}

2、结合接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public interface  {
enum DeepColor implements Color{
DEEP_BLUE,DEEP_GREEN
}
enum LightColor implements Color{
LIGHT_BLUE,LIGHT_GREEN
}
}

public class Main {
public static void main(String argr[]){
Color color = Color.DeepColor.DEEP_BLUE;
}
}

四、辅助类

1、EnumMap

key为Enum类型的Map

2、EnumSet

元素只能为Enum的Set