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

后端 未结 3 380
慢半拍i
慢半拍i 2021-01-20 05:08

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

3条回答
  •  一生所求
    2021-01-20 06:09

    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> itemsByType =
        new EnumMap<>(LibraryItemType.class);
    

提交回复
热议问题