从没有枚举的时代说起
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public class Entity { public static final int VIDEO = 1 ; //视频 public static final int AUDIO = 2 ; //音频 public static final int TEXT = 3 ; //文字 public static final int IMAGE = 4 ; //图片 private int id; private int type; public int getId() { return id; } public void setId( int id) { this .id = id; } public int getType() { return type; } public void setType( int type) { this .type = type; } } |
1
2
3
|
Entity e = new Entity(); e.setId( 10 ); e.setType( 2 ); |
认识枚举
使用枚举解决我们前面遇到的问题
1
2
3
|
public enum TypeEnum { VIDEO, AUDIO, TEXT, IMAGE } |
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
|
public class Entity { private int id; private TypeEnum type; public int getId() { return id; } public void setId( int id) { this .id = id; } public TypeEnum getType() { return type; } public void setType(TypeEnum type) { this .type = type; } } |
1
2
3
|
Entity e = new Entity(); e.setId( 10 ); e.setType(TypeEnum.AUDIO); |
01
02
03
04
05
06
07
08
09
10
11
12
13
|
public enum TypeEnum { VIDEO( 1 ), AUDIO( 2 ), TEXT( 3 ), IMAGE( 4 ); int value; TypeEnum( int value) { this .value = value; } public int getValue() { return value; } } |
1
2
|
TypeEnum type = TypeEnum.TEXT; //type的value属性值为3。 System.out.println(type.getValue()); //屏幕输出3。 |
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
|
public enum TypeEnum { VIDEO( 1 , "视频" ), AUDIO( 2 , "音频" ), TEXT( 3 , "文本" ), IMAGE( 4 , "图像" ); int value; String name; TypeEnum( int value, String name) { this .value = value; this .name = name; } public int getValue() { return value; } public String getName() { return name; } } |
1
2
3
4
5
6
7
|
int compareTo(E o) //比较此枚举与指定对象的顺序。 Class<E> getDeclaringClass() //返回与此枚举常量的枚举类型相对应的 Class 对象。 String name() // 返回此枚举常量的名称,在其枚举声明中对其进行声明。 int ordinal() //返回枚举常量的序数(它在枚举声明中的位置,其中初始常量序数为零)。 String toString() //返回枚举常量的名称,它包含在声明中。 static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) //返回带指定名称的指定枚举类型的枚举常量。 static T[] values() //返回该枚举的所有值。 |
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public enum TypeEnum { VIDEO( 1 , "视频" ), AUDIO( 2 , "音频" ), TEXT( 3 , "文本" ), IMAGE( 4 , "图像" ); int value; String name; TypeEnum( int value, String name) { this .value = value; this .name = name; } public int getValue() { return value; } public String getName() { return name; } public static TypeEnum getByValue( int value) { for (TypeEnum typeEnum : TypeEnum.values()) { if (typeEnum.value == value) { return typeEnum; } } throw new IllegalArgumentException( "No element matches " + value); } } |
原文:https://www.cnblogs.com/zhuxiaopijingjing/p/12258691.html