各种集合key,value能否为null

 

转:

各种集合key,value能否为null

HashMap

key,value都可以为null

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

key只能有一个为null,多个key=null的会覆盖,value可以多个为null

        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(1, null);
        map.put(2, null);
        map.put(null, 1);
        map.put(null, 2);
        System.out.println(map);//{null=2, 1=null, 2=null}

Hashtable

key,value都不能为null

        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();

直接调用key.hashcode方法,所以key不能为null
value为null,抛出空指针

ConcurrentHashMap

key,value都不能为null

        if (key == null || value == null) throw new NullPointerException();
        int hash = spread(key.hashCode());

key或value为null,抛出空指针
key调用hashcode方法后,用spread方法二次hash

TreeMap

key不能为null,value可以为null

            if (key == null)
                throw new NullPointerException();

key为null,抛出空指针

posted @ 2019-07-22 15:10  戈博折刀  阅读(1729)  评论(0编辑  收藏  举报