java enum 举例

1、定义一个enum

public enum Grade { A, B, C, D, F, INCOMPLETE };

2、使用一个enum

private Grade grade;

public void assignGrade(Grade grade) {
this.grade = grade;
}

public Grade getGrade() {
return grade;
}

public void testGradeAssignment(PrintStream out) throws IOException {
student1.assignGrade(Grade.B);
student2.assignGrade(Grade.INCOMPLETE);
student3.assignGrade(Grade.A);
}

3、类内声明Enum

public class Downloader {

public enum DownloadStatus { INITIALIZING, IN_PROGRESS, COMPLETE };

// Class body

}

PS.Enum默认是static的,就像interface默认是abstract的一样。

4、遍历Enum

重要是values()这个方法,它返回该类型所有可能取值的集合。

public void listGradeValues(PrintStream out) throws IOException {
Grade[] gradeValues = Grade.values();

// for loop
for (int i=0; i<gradeValues.length; i++) {
out.println(“Allowed value: ‘” + gradeValues[i] + “‘”);
}

// for/in loop
for (Grade g : gradeValues ) {
out.println(“Allowed value: ‘” + g + “‘”);
}
}

5、Enum对switch的支持

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;
}

6、EnumMap的使用

public enum AntStatus {
INITIALIZING,
COMPILING,
COPYING,
JARRING,
ZIPPING,
DONE,
ERROR
}

public class AntStatusTester {

public AntStatusTester() { }

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));
}
}

public static void main(String[] args) {
try {
AntStatusTester tester = new AntStatusTester();

tester.testEnumMap(System.out);
} catch (IOException e) {
e.printStackTrace();
}
}
}

7、Enum中添加method

public enum xxx{

xxx(){

}//构造函数

public int getXxx(){

}//接口

}

package com.test4;

public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}

package com.test4;

public class EnumTest {
Day day;

public EnumTest(Day day) {
this.day = day;
}

public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;

case FRIDAY:
System.out.println("Fridays are better.");
break;

case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;

default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.tellItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.tellItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.tellItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.tellItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.tellItLikeItIs();
}
}

结果:

Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.

声明:本文采用 BY-NC-SA 协议进行授权,本文链接:java enum 举例

发表评论