zoukankan      html  css  js  c++  java
  • 各种集合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,抛出空指针

  • 相关阅读:
    WinForm画网格并填充颜色
    CodeCombat最后一题GridMancer
    TeeChart缩放
    TeeChart的网络资料
    TeeChart设置图表的标题
    TeeChart取消3D
    TeeChart的坐标轴
    TeeChart入门
    win7下配置IIS
    C#中的编译开关
  • 原文地址:https://www.cnblogs.com/libin6505/p/11225980.html
Copyright © 2011-2022 走看看