站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题整理:J2SE5枚举使用范例

整理:J2SE5枚举使用范例

摘要: 整理:J2SE5枚举使用范例
一、定义枚举
public enum Grade {
A, B, C, D, F, INCOMPLETE
};

二、遍历枚举值
public void listGradeValues(PrintStream out) throws IOException {
for (Grade g : Grade.values()) {
out.println("Allowed value: '" + g + "'");
}
}

三、在switch中使用enum
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;
default:
outputText.append(" has a grade of ")
.append(student1.getGrade().toString());
break;
}

out.println(outputText.toString());
}


四、联合使用枚举和集合
public enum AntStatus {
INITIALIZING,
COMPILING,
COPYING,
JARRING,
ZIPPING,
DONE,
ERROR
}

public void testEnumMap(PrintStream out) throws IOException {
// Create a map with the key and a String message
EnumMap antMessages =
new EnumMap(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));
}
}

Tiger 把枚举当作类,这可以从AntStatusClass 对象那里得到证明,该对象不仅可用,而且正被实际使用。归根到底, Tiger 还是把枚举看成是特殊的类类型。


↑返回目录
前一篇: 学习笔记-标签使用(J2SE5.0)中的元数据
后一篇: J2SE5.0新特性之ProcessBuilder