简单的枚举
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //分号是可选的
}
每个枚举类型的成员是定义的枚举类型的一个实例,他们都是public static final。
简单使用:
import java.util.*;
enum OperatingSystems {
windows, unix, linux, macintosh
}
public class EnumExample1 {
public static void main(String args[])
{
OperatingSystems os;
os = OperatingSystems.windows;
switch(os) {
case windows:
System.out.println("You chose Windows!");
break;
case unix:
System.out.println("You chose Unix!");
break;
case linux:
System.out.println("You chose Linux!");
break;
case macintosh:
System.out.println("You chose Macintosh!");
break;
default:
System.out.println("I don't know your OS.");
break;
}
}
}
在一个类中的枚举
,元素则可以使用诸如 Outter.Color.RED, Outter.Color.BLUE等取得public class Outter {
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE
}
}
重载 toString 方法的枚举
.
public enum Color {
WHITE, BLACK, RED, YELLOW, BLUE; //分号是必须的。
@Override public String toString() {
//only capitalize the first letter
String s = super.toString();
return s.substring(0, 1) + s.substring(1).toLowerCase();
}
}
带有额外成员和自定义构造方法的枚举。
Enum 构造方法要么是private要么是default
public enum Color {
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);
private int code;
private Color(int c) {
code = c;
}
public int getCode() {
return code;
}
实现了接口的枚举
. 它隐含实现了 java.io.Serializable
和 java.lang.Comparable
两个接口。
public enum Color implements Runnable {
WHITE, BLACK, RED, YELLOW, BLUE;
public void run() {
System.out.println("name()=" + name() +
", toString()=" + toString());
}
}
测试一下 run() 方法:for(Color c : Color.values()) {
c.run();
}
或者
for(Runnable r : Color.values()) {
r.run();
}
常用操作
:
枚举定义:
public enum Shape { RECTANGLE, CIRCLE, LINE }
枚举声明赋值:
Shape drawing = Shape.RECTANGLE; // Only a Shape value can be assigned.
获取枚举值:
System.out.println(drawing); // Prints RECTANGLE
遍历枚举:
for (Shape shp : Shape.values()) {
System.out.println(shp); // Prints RECTANGLE, CIRCLE, ...
}
Switch判断:
switch (drawing) {
case RECTANGLE: g.drawRect(x, y, width, height);
break;
case CIRCLE : g.drawOval(x, y, width, height);
break;
case LINE : g.drawLine(x, y, x + width, y + height);
break;
}
取得索引值:
System.out.println(drawing.ordinal()); // Prints 0 for RECTANGLE.
获取输入:
drawing = Shape.valueOf
(in.next());//从in中获取字符串放入枚举中。
如何让我们的枚举Switch没有任何问题:
Colour col = ...
@CompleteEnumSwitch
switch (col) {
case RED:
// do stuff with red
break;
case BLUE:
// do stuff with blue
break;
case GREEN:
// do stuff with green
break;
}
47万+

被折叠的 条评论
为什么被折叠?



