您已经知道,Java 代码的两个基本的构造块是 类和 接口。现在 Tiger 又引入了 枚举,一般简称它为 enum。这个新类型允许您表示特定的数据点,这些数据点只接受分配时预先定义的值集合。
当然,熟练的程序员可以用静态常量实现这项功能,如下所示:
public
class
OldGrade
{
public static final int A = 1;
public static final int B = 2;
public static final int C = 3;
public static final int D = 4;
public static final int F = 5;
public static final int INCOMPLETE = 6;
}
public static final int A = 1;
public static final int B = 2;
public static final int C = 3;
public static final int D = 4;
public static final int F = 5;
public static final int INCOMPLETE = 6;
}
在使用
enum
关键字创建新的枚举类型时,实际上是在创建
java.lang.Enum
类的子类,其中,枚举类型符合通用模式
Class Enum<E extends Enum<E>>
,而
E
表示枚举类型的名称。枚举类型的每一个值都将映射到
protected Enum(String name, int ordinal)
构造函数中,在这里,每个值的名称都被转换成一个字符串,并且序数设置表示了每个设置的优先值。
package
com.uucell.util;
public enum Country {
中国(2), 德国(3), 法国(4), 英国(6);
private int value;
Country(int arg1) {
value = arg1;
}
public int getValue() {
return value;
}
}
package com.uucell.util;
import junit.framework.TestCase;
public class TT extends TestCase {
private enum Seasons {
winter, spring, summer, fall
}
public void testtt() {
for (Grade g : Grade.values()) {
System.out.println("grade value: '" + g + "'");
}
for (Country g : Country.values()) {
System.out.println("grade value: '" + g + "' " + g.getValue());
}
System.out.println(Country.中国.getValue());
for (int i = 1; i < 4; i++) {
System.out.println(Country.values()[i].getValue());
}
}
}
public enum Country {
中国(2), 德国(3), 法国(4), 英国(6);
private int value;
Country(int arg1) {
value = arg1;
}
public int getValue() {
return value;
}
}
package com.uucell.util;
import junit.framework.TestCase;
public class TT extends TestCase {
private enum Seasons {
winter, spring, summer, fall
}
public void testtt() {
for (Grade g : Grade.values()) {
System.out.println("grade value: '" + g + "'");
}
for (Country g : Country.values()) {
System.out.println("grade value: '" + g + "' " + g.getValue());
}
System.out.println(Country.中国.getValue());
for (int i = 1; i < 4; i++) {
System.out.println(Country.values()[i].getValue());
}
}
}