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,抛出空指针

  • 相关阅读:
    # GIT团队实战博客
    # ML学习小笔记—Where does the error come from?
    # Alpha冲刺3
    # Alpha冲刺2
    # Alpha冲刺1
    # ML学习小笔记—Linear Regression
    # 需求分析报告
    # 团队UML设计
    # 团队选题报告
    Alpha 冲刺 (4/10)
  • 原文地址:https://www.cnblogs.com/libin6505/p/11225980.html
Copyright © 2011-2022 走看看