Java Enum 与 Enum 关联
时间: 2023-08-01 08:07:37 浏览: 178
Java枚举类enum介绍
5星 · 资源好评率100%
Java Enum 也可以和另一个 Enum 关联起来,这种情况下可以使用 EnumMap 或者 EnumSet。
1. EnumMap
EnumMap 是一种特殊的 Map,它的 key 必须是 Enum 类型。可以用来将一个 Enum 和另一个 Enum 关联起来,例如:
```java
public enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public enum Weather {
SUNNY, RAINY, CLOUDY, SNOWY
}
public class Example {
private static final Map<Weekday, Weather> weatherMap = new EnumMap<>(Weekday.class);
static {
weatherMap.put(Weekday.MONDAY, Weather.SUNNY);
weatherMap.put(Weekday.TUESDAY, Weather.CLOUDY);
weatherMap.put(Weekday.WEDNESDAY, Weather.RAINY);
weatherMap.put(Weekday.THURSDAY, Weather.SUNNY);
weatherMap.put(Weekday.FRIDAY, Weather.SNOWY);
weatherMap.put(Weekday.SATURDAY, Weather.CLOUDY);
weatherMap.put(Weekday.SUNDAY, Weather.RAINY);
}
public static void main(String[] args) {
System.out.println(weatherMap.get(Weekday.MONDAY)); // SUNNY
}
}
```
在上面的例子中,我们使用 EnumMap 将 Weekday 枚举和 Weather 枚举关联起来。
2. EnumSet
EnumSet 是一种特殊的 Set,它的元素必须是 Enum 类型。可以用来将一个 Enum 和另一个 Enum 关联起来,例如:
```java
public enum Weekday {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public enum Weekend {
SATURDAY, SUNDAY
}
public class Example {
private static final Set<Weekday> weekdays = EnumSet.of(
Weekday.MONDAY, Weekday.TUESDAY, Weekday.WEDNESDAY,
Weekday.THURSDAY, Weekday.FRIDAY
);
public static void main(String[] args) {
System.out.println(weekdays.contains(Weekday.MONDAY)); // true
System.out.println(weekdays.contains(Weekday.SATURDAY)); // false
}
}
```
在上面的例子中,我们使用 EnumSet 将 Weekday 枚举和 Weekend 枚举关联起来,将工作日和周末分别加入不同的 EnumSet 中。
阅读全文