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]
}
}
通过使用枚举类型,您可以简化逻辑,提高代码的可读性和可维护性。