简体   繁体   中英

how to create an EnumMap object with key and value both as Enum?

enum Month{JANUARY, FEBRUARY, MARCH, ...
}

enum Week{MONDAY, TUESDAY, WEDNESDAY, ...
}

Map<Month, String> monthMap = new EnumMap<>(Month.class); Simple EnumMap can be created like this where key is Enum and value is String

However, I want to create the EnumMap where key and value both are of enum type.

Map<Month, Week> monthWeekMap = new EnumMap<> ....
what will be the syntax for creating the above enum map objet.

The syntax is no different:

Map<Month, Week> monthWeekMap = new EnumMap<>(Month.class);

The EnumMap constructor only needs the Class of the key type, in order to decide how to allocate the array used for the actual storage (an EnumMap is effectively just a strongly-typed array, whose length is the number of elements in the enum: this is obtained by reflection); the value type is essentially irrelevant, because it's just storing Object values internally.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM