【转载】 原文链接 - (部分修改与补充)
1. 概述
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.
EnumMap是是一种键为枚举类型的特殊的Map实现。所有的Key也必须是一种枚举类型,EnumMap是使用数组来实现的。(两个数组,一个数组keyUniverse存储key,另一个数组vals存储val,两个数组通过下标对应起来)
1 | EnumMap<Course, String> map = new EnumMap<Course, String>(Course.class); |
输出结果(按照枚举类中的顺序遍历数组,按数组下标依次输出(跳过空))为:
1 | ONE: 政治 |
其具体实现的结构如下图所示:

2. put和get方法
put方法通过key的ordinal将值存储到对应的地方,get方法则根据key的ordinal获取对应的值。
1 | public V put(K key, V value) { |
3. 遍历
EnumMapIterator的迭代这样实现的:
1 | public boolean hasNext() { |
通过hasNext跳过空的数组,也就是说,保证了遍历顺序与Enum中key的先后顺序一致。