java枚举类型小结

JDK5.0之前,我们一般选择使用 interface 来保存常量组,以此来弥补 JDK 中没有枚举类型的缺陷,从JDK5.0开始,Sun引进了一个全新的关键字 enum 来定义一个枚举类。同interface相比,enum 在功能上更为专业和强大。

先上个例子:


package com.darkmi.basic;

enum Color{
DARK, RED, BLUE;
}

public class EnumTest {

public static void main(String[] args) {
System.out.println(Color.BLUE);

}

}

说明:
标识符 DARK、RED、BLUE被称为枚举常量(enumeration constants)。每一个枚举常量被隐式的声明为Color的public、static成员,而且其类型为Color,也就是说这些常量是self-typed的。

遍历枚举类型:


package com.darkmi.basic;

enum Color{
DARK, RED, BLUE;
}

public class EnumTest {

public static void main(String[] args) {
for(Color color : Color.values()){
System.out.println(color);
}
}

}

switch句型:


package com.darkmi.basic;

enum Color {
DARK, RED, BLUE;
}

public class EnumTest {

public static void main(String[] args) {

Color color = Color.BLUE;

switch (color) {
case DARK:
System.out.println(“黑色”);
break;
case RED:
System.out.println(“红色”);
break;
case BLUE:
System.out.println(“蓝色”);
break;
}
}
}

说明:
(1)注意在case标签中,不使用Color.DARK,这是非法的。

关于枚举类型的特性说明:

1.它不能有public的构造函数,这样做可以保证客户代码没有办法新建一个enum的实例。

2.所有枚举值都是public , static , final的。注意这一点只是针对于枚举值,我们可以和在普通类里面定义 变量一样定义其它任何类型的非枚举变量,这些变量可以用任何你想用的修饰符。

3.Enum默认实现了java.lang.Comparable接口。

4.Enum覆载了了toString方法,因此我们如果调用Color.Blue.toString()默认返回字符串”Blue”.

5.Enum提供了一个valueOf方法,这个方法和toString方法是相对应的。调用valueOf(“Blue”)将返回Color.Blue.因此我们在自己重写toString方法的时候就要注意到这一点,一把来说应该相对应地重写valueOf方法。

6.Enum还提供了values方法,这个方法使你能够方便的遍历所有的枚举值。

7.Enum还有一个oridinal的方法,这个方法返回枚举值在枚举类种的顺序,这个顺序根据枚举值声明的顺序而定,这里Color.Red.ordinal()返回0。

以下摘自o’relly 出版的 Java in A Nutshell 5th:

Enumerated types have no public constructor. The only instances of an enumerated type are those declared by the enum.

Enums are not Cloneable, so copies of the existing instances cannot be created.

Enums implement java.io.Serializable so they can be serialized, but the Java serialization mechanism handles them specially to ensure that no new instances are ever created.

Instances of an enumerated type are immutable: each enum value retains its identity. (We’ll see later in this chapter that you can add your own fields and methods to an enumerated type, which means that you can create enumerated values that have mutable portions. This is not recommended, but does not affect the basic identity of each value.)

Instances of an enumerated type are stored in public static final fields of the type itself. Because these fields are final, they cannot be overwritten with inappropriate values: you can’t assign the DownloadStatus.ERROR value to the DownloadStatus.DONE field, for example.

By convention, the values of enumerated types are written using all capital letters, just as other static final fields are.

Because there is a strictly limited set of distinct enumerated values, it is always safe to compare enum values using the = = operator instead of calling the equals() method.

Enumerated types do have a working equals( ) method, however. The method uses = =finalso that it cannot be overridden. This working equals( ) method allows enumerated values to be used as members of collections such as Set, List, and Map. internally and is

Enumerated types have a working hashCode() method consistent with their equals( )equals(), hashCode( ) is final. It allows enumerated values to be used with classes like java.util.HashMap. method. Like

Enumerated types implement java.lang.Comparable, and the compareTo() method orders enumerated values in the order in which they appear in the enum declaration.

Enumerated types include a working toString( ) method that returns the name of the enumerated value. For example, DownloadStatus.DONE.toString( ) returns the string “DONE” by default. This method is not final, and enum types can provide a custom implementation if they choose.

Enumerated types provide a static valueOf( ) method that does the opposite of the default
toString( ) method. For example, DownloadStatus.valueOf(“DONE”) would return DownloadStatus.DONE.

Enumerated types define a final instance method namedordinal()that returns an integer for each enumerated value. The ordinal of an enumerated value represents its position (starting at zero) in the list of value names in the enum declaration. You do not typically need to use the ordinal( ) method, but it is used by a number of enum-related facilities, as described later in the chapter.

Each enumerated type defines a static method named values( ) that returns an array of enumerated values of that type. This array contains the complete set of values, in the order they were declared, and is useful for iterating through the complete set of possible values. Because arrays are mutable, the values( ) method always returns a newly created and initialized array.

Enumerated types are subclasses of java.lang.Enum, which is new in Java 5.0. (Enum is not itself an enumerated type.) You cannot produce an enumerated type by manually extending the Enum class, and it is a compilation error to attempt this. The only way to define an enumerated type is with the enum keyword.

It is not possible to extend an enumerated type. Enumerated types are effectively final, but the final keyword is neither required nor permitted in their declarations. Because enums are effectively final, they may not be abstract.

Like classes, enumerated types may implement one or more interfaces.

两篇文章:

枚举类型入门
http://www.ibm.com/developerworks/cn/java/j-enums.html

驯服 Tiger: 深入研究枚举类型
http://www.ibm.com/developerworks/cn/java/j-tiger04195/

JDK的API说明:http://download.oracle.com/javase/6/docs/api/java/lang/Enum.html

此条目发表在java/j2ee分类目录,贴了, 标签。将固定链接加入收藏夹。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据