如果我们将null键添加为Object,为什么synchronized对象会给出null指针Exception。

时间:2016-04-26 12:44:41

标签: java serialization concurrenthashmap

这里我有哈希表和并发哈希映射的代码示例,它不允许将null键作为对象但是两者都是同步的。

  public class Example
  {
public static void main(String[] args)
{
    ConcurrentHashMap<String,String> premiumPhone = 
                           new ConcurrentHashMap<String,String>();
    premiumPhone.put("Apple", "iPhone");
    premiumPhone.put("HTC", "HTC one");
    premiumPhone.put(null,"S5");

    Iterator iterator = premiumPhone.keySet().iterator();

    while (iterator.hasNext())
    {
        System.out.println(premiumPhone.get(iterator.next()));
        premiumPhone.put("Sony", "Xperia Z");
    }

}
}

1 个答案:

答案 0 :(得分:2)

来自ConcurrentHashMap的Javadoc

  

与Hashtable类似,但与HashMap不同,此类不允许使用null   用作键或值。

https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html

另外,请看一下:https://stackoverflow.com/a/9298113/2227788