Andrey Andrey - 1 year ago 59
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?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download