概念
enum
的全稱為 enumeration, 是 JDK 1.5 中引入的新特性。
在Java中,被 enum
關(guān)鍵字修飾的類型就是枚舉類型。形式如下:
1
|
enum Color { RED, GREEN, BLUE } |
如果枚舉不添加任何方法,枚舉值默認(rèn)為從0開始的有序數(shù)值。以 Color 枚舉類型舉例,它的枚舉常量依次為RED:0,GREEN:1,BLUE:2
枚舉的好處:可以將常量組織起來,統(tǒng)一進(jìn)行管理。
枚舉的典型應(yīng)用場景:錯(cuò)誤碼、狀態(tài)機(jī)等。
枚舉類型的本質(zhì)
盡管enum
看起來像是一種新的數(shù)據(jù)類型,事實(shí)上,enum是一種受限制的類,并且具有自己的方法。
創(chuàng)建enum時(shí),編譯器會為你生成一個(gè)相關(guān)的類,這個(gè)類繼承自 java.lang.Enum
。
java.lang.Enum
類聲明
1
2
|
public abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable { ... } |
枚舉的方法
在enum中,提供了一些基本方法:
values()
:返回enum實(shí)例的數(shù)組,而且該數(shù)組中的元素嚴(yán)格保持在enum中聲明時(shí)的順序。
name()
:返回實(shí)例名。
ordinal()
:返回實(shí)例聲明時(shí)的次序,從0開始。
getDeclaringClass()
:返回實(shí)例所屬的enum類型。
equals()
:判斷是否為同一個(gè)對象。
可以使用 ==
來比較enum
實(shí)例。
此外,java.lang.Enum
實(shí)現(xiàn)了Comparable
和 Serializable
接口,所以也提供 compareTo() 方法。
例:展示enum的基本方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class EnumMethodDemo { enum Color {RED, GREEN, BLUE;} enum Size {BIG, MIDDLE, SMALL;} public static void main(String args[]) { System.out.println( "=========== Print all Color ===========" ); for (Color c : Color.values()) { System.out.println(c + " ordinal: " + c.ordinal()); } System.out.println( "=========== Print all Size ===========" ); for (Size s : Size.values()) { System.out.println(s + " ordinal: " + s.ordinal()); } Color green = Color.GREEN; System.out.println( "green name(): " + green.name()); System.out.println( "green getDeclaringClass(): " + green.getDeclaringClass()); System.out.println( "green hashCode(): " + green.hashCode()); System.out.println( "green compareTo Color.GREEN: " + green.compareTo(Color.GREEN)); System.out.println( "green equals Color.GREEN: " + green.equals(Color.GREEN)); System.out.println( "green equals Size.MIDDLE: " + green.equals(Size.MIDDLE)); System.out.println( "green equals 1: " + green.equals( 1 )); System.out.format( "green == Color.BLUE: %b\n" , green == Color.BLUE); } } |
輸出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
=========== Print all Color =========== RED ordinal: 0 GREEN ordinal: 1 BLUE ordinal: 2 =========== Print all Size =========== BIG ordinal: 0 MIDDLE ordinal: 1 SMALL ordinal: 2 green name(): GREEN green getDeclaringClass(): class org.zp.javase.enumeration.EnumDemo$Color green hashCode(): 460141958 green compareTo Color.GREEN: 0 green equals Color.GREEN: true green equals Size.MIDDLE: false green equals 1: false green == Color.BLUE: false |
枚舉的特性
枚舉的特性,歸結(jié)起來就是一句話:
除了不能繼承,基本上可以將enum
看做一個(gè)常規(guī)的類。
但是這句話需要拆分去理解,讓我們細(xì)細(xì)道來。
枚舉可以添加方法
在概念章節(jié)提到了,枚舉值默認(rèn)為從0開始的有序數(shù)值 。那么問題來了:如何為枚舉顯示的賦值。
Java 不允許使用 =
為枚舉常量賦值
如果你接觸過C/C++,你肯定會很自然的想到賦值符號 =
。在C/C++語言中的enum,可以用賦值符號=顯示的為枚舉常量賦值;但是 ,很遺憾,Java 語法中卻不允許使用賦值符號 = 為枚舉常量賦值。
例:C/C++ 語言中的枚舉聲明
1
2
3
4
5
6
|
typedef enum { ONE = 1, TWO, THREE = 3, TEN = 10 } Number; |
enum 可以添加普通方法、靜態(tài)方法、抽象方法、構(gòu)造方法
Java雖然不能直接為實(shí)例賦值,但是它有更優(yōu)秀的解決方案:為 enum 添加方法來間接實(shí)現(xiàn)顯示賦值。
創(chuàng)建 enum
時(shí),可以為其添加多種方法,甚至可以為其添加構(gòu)造方法。
注意一個(gè)細(xì)節(jié):如果要為enum定義方法,那么必須在enum的最后一個(gè)實(shí)例尾部添加一個(gè)分號。此外,在enum中,必須先定義實(shí)例,不能將字段或方法定義在實(shí)例前面。否則,編譯器會報(bào)錯(cuò)。
例:全面展示如何在枚舉中定義普通方法、靜態(tài)方法、抽象方法、構(gòu)造方法
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
|
public enum ErrorCode { OK( 0 ) { public String getDescription() { return "成功" ; } }, ERROR_A( 100 ) { public String getDescription() { return "錯(cuò)誤A" ; } }, ERROR_B( 200 ) { public String getDescription() { return "錯(cuò)誤B" ; } }; private int code; // 構(gòu)造方法:enum的構(gòu)造方法只能被聲明為private權(quán)限或不聲明權(quán)限 private ErrorCode( int number) { // 構(gòu)造方法 this .code = number; } public int getCode() { // 普通方法 return code; } // 普通方法 public abstract String getDescription(); // 抽象方法 public static void main(String args[]) { // 靜態(tài)方法 for (ErrorCode s : ErrorCode.values()) { System.out.println( "code: " + s.getCode() + ", description: " + s.getDescription()); } } } |
注:上面的例子并不可取,僅僅是為了展示枚舉支持定義各種方法。下面是一個(gè)簡化的例子
例:一個(gè)錯(cuò)誤碼枚舉類型的定義
本例和上例的執(zhí)行結(jié)果完全相同。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public enum ErrorCodeEn { OK( 0 , "成功" ), ERROR_A( 100 , "錯(cuò)誤A" ), ERROR_B( 200 , "錯(cuò)誤B" ); ErrorCodeEn( int number, String description) { this .code = number; this .description = description; } private int code; private String description; public int getCode() { return code; } public String getDescription() { return description; } public static void main(String args[]) { // 靜態(tài)方法 for (ErrorCodeEn s : ErrorCodeEn.values()) { System.out.println( "code: " + s.getCode() + ", description: " + s.getDescription()); } } } |
枚舉可以實(shí)現(xiàn)接口
enum
可以像一般類一樣實(shí)現(xiàn)接口。
同樣是實(shí)現(xiàn)上一節(jié)中的錯(cuò)誤碼枚舉類,通過實(shí)現(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
|
public interface INumberEnum { int getCode(); String getDescription(); } public enum ErrorCodeEn2 implements INumberEnum { OK( 0 , "成功" ), ERROR_A( 100 , "錯(cuò)誤A" ), ERROR_B( 200 , "錯(cuò)誤B" ); ErrorCodeEn2( int number, String description) { this .code = number; this .description = description; } private int code; private String description; @Override public int getCode() { return code; } @Override public String getDescription() { return description; } } |
枚舉不可以繼承
enum 不可以繼承另外一個(gè)類,當(dāng)然,也不能繼承另一個(gè) enum 。
因?yàn)?code style="font-size: 0.93em; font-family: 'Source Code Pro',Consolas,Menlo,Monaco,'Courier New',monospace; white-space: pre; color: rgb(199,37,78); padding-bottom: 2px; padding-top: 2px; padding-left: 4px; padding-right: 4px; background-color: rgb(249,242,244)"> enum 實(shí)際上都繼承自 java.lang.Enum
類,而 Java 不支持多重繼承,所以enum不能再繼承其他類,當(dāng)然也不能繼承另一個(gè) enum
。
枚舉的應(yīng)用場景
組織常量
在JDK1.5 之前,在Java中定義常量都是public static final TYPE a
; 這樣的形式。有了枚舉,你可以將有關(guān)聯(lián)關(guān)系的常量組織起來,使代碼更加易讀、安全,并且還可以使用枚舉提供的方法。
枚舉聲明的格式
注:如果枚舉中沒有定義方法,也可以在最后一個(gè)實(shí)例后面加逗號、分號或什么都不加。
下面三種聲明方式是等價(jià)的:
1
2
3
|
enum Color { RED, GREEN, BLUE } enum Color { RED, GREEN, BLUE, } enum Color { RED, GREEN, BLUE; } |
switch 狀態(tài)機(jī)
我們經(jīng)常使用switch語句來寫狀態(tài)機(jī)。JDK7以后,switch已經(jīng)支持 int、char、String、enum
類型的參數(shù)。這幾種類型的參數(shù)比較起來,使用枚舉的switch代碼更具有可讀性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
enum Signal {RED, YELLOW, GREEN} public static String getTrafficInstruct(Signal signal) { String instruct = "信號燈故障" ; switch (signal) { case RED: instruct = "紅燈停" ; break ; case YELLOW: instruct = "黃燈請注意" ; break ; case GREEN: instruct = "綠燈行" ; break ; default : break ; } return instruct; } |
組織枚舉
可以將類型相近的枚舉通過接口或類組織起來。
但是一般用接口方式進(jìn)行組織。
原因是:Java接口在編譯時(shí)會自動為enum類型加上public static
修飾符;Java類在編譯時(shí)會自動為 enum
類型加上static
修飾符??闯霾町惲藛幔繘]錯(cuò),就是說,在類中組織 enum
,如果你不給它修飾為 public
,那么只能在本包中進(jìn)行訪問。
例:在接口中組織 enum
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
37
38
39
40
41
42
43
44
45
46
47
48
|
public interface Plant { enum Vegetable implements INumberEnum { POTATO( 0 , "土豆" ), TOMATO( 0 , "西紅柿" ); Vegetable( int number, String description) { this .code = number; this .description = description; } private int code; private String description; @Override public int getCode() { return 0 ; } @Override public String getDescription() { return null ; } } enum Fruit implements INumberEnum { APPLE( 0 , "蘋果" ), ORANGE( 0 , "桔子" ), BANANA( 0 , "香蕉" ); Fruit( int number, String description) { this .code = number; this .description = description; } private int code; private String description; @Override public int getCode() { return 0 ; } @Override public String getDescription() { return null ; } } } |
例:在類中組織 enum
本例和上例效果相同。
1
2
3
4
|
public class Plant2 { public enum Vegetable implements INumberEnum {...} // 省略代碼 public enum Fruit implements INumberEnum {...} // 省略代碼 } |
策略枚舉
EffectiveJava中展示了一種策略枚舉。這種枚舉通過枚舉嵌套枚舉的方式,將枚舉常量分類處理。
這種做法雖然沒有switch語句簡潔,但是更加安全、靈活。
例:EffectvieJava中的策略枚舉范例
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
37
38
|
enum PayrollDay { MONDAY(PayType.WEEKDAY), TUESDAY(PayType.WEEKDAY), WEDNESDAY( PayType.WEEKDAY), THURSDAY(PayType.WEEKDAY), FRIDAY(PayType.WEEKDAY), SATURDAY( PayType.WEEKEND), SUNDAY(PayType.WEEKEND); private final PayType payType; PayrollDay(PayType payType) { this .payType = payType; } double pay( double hoursWorked, double payRate) { return payType.pay(hoursWorked, payRate); } // 策略枚舉 private enum PayType { WEEKDAY { double overtimePay( double hours, double payRate) { return hours <= HOURS_PER_SHIFT ? 0 : (hours - HOURS_PER_SHIFT) * payRate / 2 ; } }, WEEKEND { double overtimePay( double hours, double payRate) { return hours * payRate / 2 ; } }; private static final int HOURS_PER_SHIFT = 8 ; abstract double overtimePay( double hrs, double payRate); double pay( double hoursWorked, double payRate) { double basePay = hoursWorked * payRate; return basePay + overtimePay(hoursWorked, payRate); } } } |
測試
1
2
|
System.out.println( "時(shí)薪100的人在周五工作8小時(shí)的收入:" + PayrollDay.FRIDAY.pay( 8.0 , 100 )); System.out.println( "時(shí)薪100的人在周六工作8小時(shí)的收入:" + PayrollDay.SATURDAY.pay( 8.0 , 100 )); |
EnumSet和EnumMap
Java中提供了兩個(gè)方便操作enum的工具類——EnumSet和EnumMap。
EnumSet
是枚舉類型的高性能Set
實(shí)現(xiàn)。它要求放入它的枚舉常量必須屬于同一枚舉類型。
EnumMap
是專門為枚舉類型量身定做的Map實(shí)現(xiàn)。雖然使用其它的Map
實(shí)現(xiàn)(如HashMap)也能完成枚舉類型實(shí)例到值得映射,但是使用EnumMap會更加高效:它只能接收同一枚舉類型的實(shí)例作為鍵值,并且由于枚舉類型實(shí)例的數(shù)量相對固定并且有限,所以EnumMap使用數(shù)組來存放與枚舉類型對應(yīng)的值。這使得EnumMap的效率非常高。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
// EnumSet的使用 System.out.println( "EnumSet展示" ); EnumSet<ErrorCodeEn> errSet = EnumSet.allOf(ErrorCodeEn. class ); for (ErrorCodeEn e : errSet) { System.out.println(e.name() + " : " + e.ordinal()); } // EnumMap的使用 System.out.println( "EnumMap展示" ); EnumMap<StateMachine.Signal, String> errMap = new EnumMap(StateMachine.Signal. class ); errMap.put(StateMachine.Signal.RED, "紅燈" ); errMap.put(StateMachine.Signal.YELLOW, "黃燈" ); errMap.put(StateMachine.Signal.GREEN, "綠燈" ); for (Iterator<Map.Entry<StateMachine.Signal, String>> iter = errMap.entrySet().iterator(); iter.hasNext();) { Map.Entry<StateMachine.Signal, String> entry = iter.next(); System.out.println(entry.getKey().name() + " : " + entry.getValue()); } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/jingmoxukong/p/6098351.html