java-map-EnumMap

  在日常的项目中,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

相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息