gpt4 book ai didi

java - 如果我们将空键添加为对象,为什么同步对象会给出空指针异常?

转载 作者:行者123 更新时间:2023-11-30 02:57:21 26 4
gpt4 key购买 nike

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

  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");
}

}
}

最佳答案

来自 ConcurrentHashMap 的 Javadoc

Like Hashtable but unlike HashMap, this class does not allow null to be used as a key or value.

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

另外,看看这个:https://stackoverflow.com/a/9298113/2227788

关于java - 如果我们将空键添加为对象,为什么同步对象会给出空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36865356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com