前言
在大家日常編程中,往往存在著這樣的“數(shù)據(jù)集”,它們的數(shù)值在程序中是穩(wěn)定的,而且“數(shù)據(jù)集”中的元素是有限的。例如星期一到星期日七個數(shù)據(jù)元素組成了一周的“數(shù)據(jù)集”,春夏秋冬四個數(shù)據(jù)元素組成了四季的“數(shù)據(jù)集”。在java中如何更好的使用這些“數(shù)據(jù)集”呢?因此枚舉便派上了用場
枚舉其實就是一種類型,跟int, char 這種差不多,就是定義變量時限制輸入的,你只能夠賦enum里面規(guī)定的值。
枚舉(enum)實現(xiàn)
JDK5中提供了Java枚舉類型的實現(xiàn),與其說是一種新類型,倒不如說是一種語法糖。
1
2
3
4
5
6
|
public enum Season { SPRING, SUMMER, AUTUMN, WINTER } |
通過反編譯工具來看看這段代碼是如何實現(xiàn)的,反編譯后的代碼如下:
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
|
public final class Season extends Enum { public static Season[] values() { return (Season[])$VALUES.clone(); } public static Season valueOf(String s) { return (Season)Enum.valueOf(Season, s); } private Season(String s, int i) { super (s, i); } public static final Season SPRING; public static final Season SUMMER; public static final Season AUTUMN; public static final Season WINTER; private static final Season $VALUES[]; static { SPRING = new Season( "SPRING" , 0 ); SUMMER = new Season( "SUMMER" , 1 ); AUTUMN = new Season( "AUTUMN" , 2 ); WINTER = new Season( "WINTER" , 3 ); $VALUES = ( new Season[] { SPRING, SUMMER, AUTUMN, WINTER }); } } |
通過反編譯的代碼可以發(fā)現(xiàn):
1、Season
是一個普通的類,繼承自Enum
,并通過final
關(guān)鍵字修飾,避免被繼承,
2、枚舉中的SPRING
、SUMMER
、AUTUMN
和WINTER
是Season
類的靜態(tài)實例,并在類構(gòu)造器<clinit>
方法中進行初始化。
3、values()
方法返回私有變量$VALUES[]
的副本,$VALUES[]
也是在<clinit>
方法中進行初始化。
如何使用枚舉(enum)
1、單例模式
我們已經(jīng)知道類構(gòu)造器<clinit>
只能被一個線程在類加載的初始化階段進行執(zhí)行,所以枚舉的每個實例在Java堆中有且只有一個副本,這種特性讓枚舉很容易就實現(xiàn)了單例模式,這也正是Effective Java作者 Josh Bloch 提倡使用實現(xiàn)單利模式的方式。
1
|
public enum Singleton { INSTANCE;} |
2、在switch中使用
3、自定義字段和方法
枚舉(enum)中除了默認(rèn)字段和方法之外,可以針對業(yè)務(wù)邏輯進行自定義。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public enum EnumTest { PLUS( "+" ) { @Override public int bind( int arg1, int arg2) { return arg1 + arg2; } }, SUB( "-" ) { @Override public int bind( int arg1, int arg2) { return arg1 - arg2; } }; final String operation; EnumTest(String operation) { this .operation = operation; } abstract int bind( int arg1, int arg2); } |
4、實現(xiàn)接口
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
|
interface Operation{ int operate( int arg1, int arg2); } public enum EnumTest implements Operation { PLUS( "+" ) { @Override public int operate( int arg1, int arg2) { return arg1 + arg2; } }, SUB( "-" ) { @Override public int operate( int arg1, int arg2) { return arg1 - arg2; } }; final String operation; EnumTest(String operation) { this .operation = operation; } } |
在實際應(yīng)用中,可以把 "+"、"-" 作為key,PLUS和SUB作為value
,預(yù)先保存在hashMap
中,具體使用方式如下:
1
2
|
Operation operation = hashMap.get( "+" ); int result = operation.bind( 1 , 2 ); |
總結(jié)
以上就是關(guān)于Java中枚舉類型的全部內(nèi)容了,希望通過本文對java中枚舉的介紹,能夠給大家?guī)韼椭H绻幸蓡柎蠹铱梢粤粞越涣鳌?/p>