java-map-EnumMap
在平常的项目中,enumMap是比较少用到的一种map,一般都不会使用到这种容器,那么我将从如下几个方面来阐述我对enumMap的理解
1、使用场景
在key是比较固定的情况下,使用enumMap是最适合不过的,如我的水果摊中,就有如下几种水果:Fruit.APPLE,Fruit.BANANA,Fruit.PEAR,Fruit.GRAPE,那么这几种水果的价格是
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");
当有人问我苹果的价格的时候,我会告诉他,苹果是这个价格
enumMap.get(enumMap.APPLE);
2、jdk说明
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,内部是使用数组来存储的,所以是非常高效和整洁的。
3、源码探索
put方法:
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方法:
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不一致的时候,将会返回null
浙公网安备 33010602011771号