How to effectively use Enum objects as keys in a map data structure?

Is there a more efficient and specialized implementation of a map collection in which Enum objects can serve as keys?

+3
source share
3 answers

I found out about this recently when I accidentally stumbled upon a response in the Java API. If you have ever had a card that uses enumerations as keys, make sure you use EnumMap . It is very simple and much more efficient:

public interface LibraryItem{ ... }

public enum LibraryItemType{ BOOK, CD, VHS, AUDIO; ... }

Map<LibraryItemType, NavigableSet<LibraryItem>> itemsByType =
    new EnumMap<>(LibraryItemType.class);
0
source

Yes. EnumMap- exactly this; efficient implementation of an interface Mapin which the key type must be an enumeration:

API documentation:

Class EnumMap<K extends Enum<K>,V>

enum. , , , . Enum . .

:

Map<MyEnum, String> map = new EnumMap<MyEnum, String>(MyEnum.class);
+18

By the way, it’s easier to write:

Map<MyEnum, String> map = new EnumMap<>(MyEnum.class);

No need to repeat types. This can make the code much easier to read.

+1
source

Source: https://habr.com/ru/post/1749761/


All Articles