枚举的作用是在编程语言中表示一组命名常量。例如,一副扑克牌中的4种花色可以表示为4个名为梅花、菱形、红桃和黑桃的枚举器,它们属于一个名为花色的枚举类型。
在Java
中,枚举使用enum
数据类型来表示,里面可以添加变量,方法和构造器。
枚举类型声明
枚举类型的声明可以在类的外面,也可以在类的里面,但是不能声明在方法内部。
// enum declared outside a class
enum Color {
RED, GREEN, BLUE;
}
public class Test {
// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}
// enum declared inside a class
public class Test {
enum Color {
RED, GREEN, BLUE;
}
// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}
常用方法
valueOf()
返回指定字符串值的枚举常量;
values()
返回枚举中存在的所有值;
ordinal()
返回枚举中常量的索引;
// Java program to demonstrate working of values(),
// ordinal() and valueOf()
enum Color {
RED, GREEN, BLUE;
}
public class Test {
public static void main(String[] args) {
// Calling values()
Color arr[] = Color.values();
// enum with loop
for (Color col : arr) {
// Calling ordinal() to find index of color.
System.out.println(col + " at index "
+ col.ordinal());
}
// Using valueOf(). Returns an object of
// Color with given constant.
// Uncommenting second line causes exception
// IllegalArgumentException
System.out.println(Color.valueOf("RED"));
// System.out.println(Color.valueOf("WHITE"));
}
}
/**
* Output:
* RED at index 0
* GREEN at index 1
* BLUE at index 2
* RED
*/
构造函数和方法
- 枚举可以包含构造函数,它在枚举类加载时为每个枚举常量单独执行
- 不能显式创建枚举对象,因此不能直接调用枚举构造函数
- 枚举只能包含具体方法,即不包含任何抽象方法
enum Color {
RED, GREEN, BLUE;
// 构造函数应用于每一个常量
private Color() {
System.out.println("Constructor called for : " +
this.toString());
}
// 只能是具体的方法,不能用 abstract 修饰
public void colorInfo() {
System.out.println("Universal Color");
}
}
public class Test {
// Driver method
public static void main(String[] args) {
// 不能显示创建枚举对象
Color c1 = Color.RED;
System.out.println(c1);
c1.colorInfo();
}
}