Andrey Andrey - 6 months ago 24
Java Question

How to efficiently use Enum objects as keys in the Map data structure?

Is there a more efficient and specialized implementation of a Map collection where Enum objects can serve as keys?


I learned this recently after I accidentally stumbled upon the answer in the Java API. If you ever have a map that uses enums as keys make sure you use EnumMap. It's very simple and much more efficient:

public interface LibraryItem{ ... }

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

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