Java 枚舉類型(Enum)是一種特殊的類,用于表示一組固定的常量值。使用枚舉類型可以簡化邏輯,提高代碼的可讀性和可維護性。以下是一些使用枚舉類型簡化邏輯的方法:
enum Color {
RED, GREEN, BLUE;
}
public class Main {
public static void main(String[] args) {
Color color = Color.RED;
switch (color) {
case RED:
System.out.println("紅色");
break;
case GREEN:
System.out.println("綠色");
break;
case BLUE:
System.out.println("藍色");
break;
}
}
}
enum Operation {
ADD {
@Override
public int apply(int a, int b) {
return a + b;
}
},
SUBTRACT {
@Override
public int apply(int a, int b) {
return a - b;
}
};
public abstract int apply(int a, int b);
}
public class Main {
public static void main(String[] args) {
System.out.println(Operation.ADD.apply(1, 2)); // 輸出 3
System.out.println(Operation.SUBTRACT.apply(1, 2)); // 輸出 -1
}
}
enum City {
NEW_YORK, LOS_ANGELES, CHICAGO;
}
public class Main {
public static void main(String[] args) {
Map<City, String> cityNames = new HashMap<>();
cityNames.put(City.NEW_YORK, "New York");
cityNames.put(City.LOS_ANGELES, "Los Angeles");
cityNames.put(City.CHICAGO, "Chicago");
System.out.println(cityNames.get(City.NEW_YORK)); // 輸出 New York
}
}
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
public class Main {
public static void main(String[] args) {
List<Day> daysOfWeek = Arrays.asList(Day.values());
System.out.println(daysOfWeek); // 輸出 [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY]
}
}
通過使用枚舉類型,您可以簡化邏輯,提高代碼的可讀性和可維護性。