【轉(zhuǎn)載】 原文鏈接 - (部分修改與補(bǔ)充)
- 更多相關(guān)文章見筆者博客
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實(shí)現(xiàn)。所有的Key也必須是一種枚舉類型,EnumMap是使用數(shù)組來(lái)實(shí)現(xiàn)的。(兩個(gè)數(shù)組,一個(gè)數(shù)組keyUniverse存儲(chǔ)key,另一個(gè)數(shù)組vals存儲(chǔ)val,兩個(gè)數(shù)組通過(guò)下標(biāo)對(duì)應(yīng)起來(lái))
EnumMap<Course, String> map = new EnumMap<Course, String>(Course.class);
map.put(Course.ONE, "語(yǔ)文");
map.put(Course.ONE, "政治");
map.put(Course.TWO, "數(shù)學(xué)");
map.put(Course.THREE, "英語(yǔ)");
for(Entry<Course, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
輸出結(jié)果(按照枚舉類中的順序遍歷數(shù)組,按數(shù)組下標(biāo)依次輸出(跳過(guò)空))為:
ONE: 政治
TWO: 數(shù)學(xué)
THREE: 英語(yǔ)
其具體實(shí)現(xiàn)的結(jié)構(gòu)如下圖所示:

2. put和get方法
put方法通過(guò)key的ordinal將值存儲(chǔ)到對(duì)應(yīng)的地方,get方法則根據(jù)key的ordinal獲取對(duì)應(yīng)的值。
public V put(K key, V value) {
// 類型檢查
typeCheck(key);
// 獲取key的序號(hào)
int index = key.ordinal();
Object oldValue = vals[index];
// 賦值
vals[index] = maskNull(value);
// 若之前的值為空,則size++
if (oldValue == null)
size++;
return unmaskNull(oldValue);
}
public V get(Object key) {
return (isValidKey(key) ?
unmaskNull(vals[((Enum<?>)key).ordinal()]) : null);
}
3. 遍歷
EnumMapIterator的迭代這樣實(shí)現(xiàn)的:
public boolean hasNext() {
while (index < vals.length && vals[index] == null)
index++;
return index != vals.length;
}
public Map.Entry<K,V> next() {
if (!hasNext())
throw new NoSuchElementException();
lastReturnedEntry = new Entry(index++);
return lastReturnedEntry;
}
通過(guò)hasNext跳過(guò)空的數(shù)組,也就是說(shuō),保證了遍歷順序與Enum中key的先后順序一致。