Java 中声明的枚举类,均是 java.lang.Enum 类的子类,Enun 类中的常用方法有:
- name() 返回枚举对象名称
- ordinal() 返回枚举对象下标
- valueOf(Class enumType, String name) 转换枚举对象
自定义的枚举类,在编译阶段自动生成下面方法
- valueOf(String name) 转换枚举对象
- values() 获得所有枚举对象数组
测试代码如下:
import java.util.Arrays;
/**
* Created by Administrator on 2018/7/20 18:41 in Beijing.
*/
public class EnumerationTest {
public static void main(String[] args) {
Color red = Color.RED;
// name 方法 返回 枚举实例 名称
System.out.println(red.name());
// ordinal 方法 返回 枚举实例 下标
System.out.println(red.ordinal());
System.out.println();
Color yellow1 = Enum.valueOf(Color.class, "YELLOW");
Color yellow2 = Color.valueOf("YELLOW");
System.out.println(yellow1);
System.out.println(yellow1.name());
System.out.println(yellow2);
System.out.println();
Color[] colors = Color.values();
System.out.println(Arrays.toString(colors));
}
}
enum Color {
BLUE, RED, YELLOW;
}
/*class Color { JDK5 前的枚举类
public static final Color BLUE = new Color();
public static final Color RED = new Color();
public static final Color YELLOW = new Color();
private Color() { }
}*/
输出如下:
RED
1
YELLOW
YELLOW
YELLOW
[BLUE, RED, YELLOW]