JAVA中枚举类型



简单的枚举
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.Serializablejava.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;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值