在日常的項目中,enumMap是比較少用到的一種map,通常都不會使用到這種容器,那麼我將從以下幾個方面來闡述我對enumMap的理解數組
一、使用場景ui
在key是比較固定的狀況下,使用enumMap是最適合不過的,如個人水果攤中,就有以下幾種水果:Fruit.APPLE,Fruit.BANANA,Fruit.PEAR,Fruit.GRAPE,那麼這幾種水果的價格是spa
EnumMap enumMap=new EnumMap(Fruit.class);
enumMap.put(Fruit.APPLE,"9/kg");
enumMap.put(Fruit.BANANA,"5/kg");
enumMap.put(Fruit.PEAR,"6/kg");
enumMap.put(Fruit.GRAPE,"20/kg");
當有人問我蘋果的價格的時候,我會告訴他,蘋果是這個價格code
enumMap.get(enumMap.APPLE);
二、jdk說明blog
A specialized {@link 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.
*
* <p>Enum maps are maintained in the <i>natural order</i> of their keys
* (the order in which the enum constants are declared). This is reflected
* in the iterators returned by the collections views ({@link #keySet()},
* {@link #entrySet()}, and {@link #values()}).
也就是說,enumMap是一個支持使用enum類型做爲key的map,內部是使用數組來存儲的,因此是很是高效和整潔的。
三、源碼探索ci
put方法:rem
1 public V put(K key, V value) { 2 typeCheck(key); 3 4 int index = key.ordinal(); 5 Object oldValue = vals[index]; 6 vals[index] = maskNull(value); 7 if (oldValue == null) 8 size++; 9 return unmaskNull(oldValue); 10 } 11 private V unmaskNull(Object value) { 12 return (V)(value == NULL ? null : value); 13 }
從這個看出,若是key是null,則會拋出NullPointerException,若是這個key對應的值若是有舊值,就會使用舊值來代替新值。get
get方法:源碼
public V get(Object key) { return (isValidKey(key) ? unmaskNull(vals[((Enum<?>)key).ordinal()]) : null); } private V unmaskNull(Object value) { return (V)(value == NULL ? null : value); }
在get方法中,若是key和你的keyType不一致的時候,將會返回nullit