public void testSwitchStatement(PrintStream out) throws IOException {
StringBuffer outputText = new StringBuffer(student1.getFullName());
switch (student1.getGrade()) {
case A:
outputText.append(" excelled with a grade of A");
break;
case B: // fall through to C
case C:
outputText.append(" passed with a grade of ")
.append(student1.getGrade().toString());
break;
case D: // fall through to F
case F:
outputText.append(" failed with a grade of ")
.append(student1.getGrade().toString());
break;
case INCOMPLETE:
outputText.append(" did not complete the class.");
break;
}
out.println(outputText.toString());
}
在这里,枚举值被传递到 switch 语句中(请记住,getGrade() 是作为 Grade 的实例返回的),而每个 case 子句将处理一个特定的值。该值在提供时没有枚举前缀,这意味着不用将代码写成 case Grade.A,只需将其写成 case A 即可。如果您不这么做,编译器不会接受有前缀的值。
枚举的映射(Map)
public void testEnumMap(PrintStream out) throws IOException {
// Create a map with the key and a String message
EnumMap<AntStatus, String> antMessages =
new EnumMap<AntStatus, String>(AntStatus.class);
// Initialize the map
antMessages.put(AntStatus.INITIALIZING, "Initializing Ant...");
antMessages.put(AntStatus.COMPILING, "Compiling Java classes...");
antMessages.put(AntStatus.COPYING, "Copying files...");
antMessages.put(AntStatus.JARRING, "JARring up files...");
antMessages.put(AntStatus.ZIPPING, "ZIPping up files...");
antMessages.put(AntStatus.DONE, "Build complete.");
antMessages.put(AntStatus.ERROR, "Error occurred.");
// Iterate and print messages
for (AntStatus status : AntStatus.values() ) {
out.println("For status " + status + ", message is: " +
antMessages.get(status));
}
}
该代码使用了泛型(generics和新的 EnumMap 构造来建立新映射。而且,枚举值是通过其 Class 对象提供的,同时提供的还有映射值的类型(在该例中,它只是一个简单的字符串)。