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

后端 未结 3 465
慢半拍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条回答
  •  萌比男神i
    2021-01-20 05:51

    Yes. EnumMap is precisely that; an efficient implementation of the Map interface, in which the key type must be an enum:

    From the API documentation:

    Class EnumMap,V>

    A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

    Example usage:

    Map map = new EnumMap(MyEnum.class);
    

提交回复
热议问题