gpt4 book ai didi

java - 获取大小时 map 的空指针异常

转载 作者:行者123 更新时间:2023-11-29 05:18:00 26 4
gpt4 key购买 nike

当我们将 null Map 放入 Map 后获取大小时,它会抛出 Null Pointer Exception。当我们知道HashMap是允许放null值和key的时候。为什么当我们放置 null Map 时会发生这种情况。

public static void main(String[] args){
Map<String, Integer> n=new HashMap<String, Integer>();
n.put("1", 1);
System.out.println(n.size());
Map<String, Integer> nn=null;
n.putAll(nn);
System.out.println(n.size());
}

最佳答案

您没有让 NPE 调用 n.size();调用 n.putAll(nn) 时,您在前一行得到了 NPE。尽管 HashMap 中的单个键和值允许为 null,但 putAll 的 map 参数却不允许。 The documentation of HashMap.putAll说:

throws NullPointerException - if the specified map is null

如果你想 putAll 0 个条目,你可以使用一个非空的空映射。

关于java - 获取大小时 map 的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25862306/

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