Map.keySet() 和 Set.addAll 抛出 NullPoniterException
这是一个旧代码,正在调试它。 我有一个 Map
(myMap),大小为 2(当然)。键为 null
和 1
。
SortedSet mySet = new TreeSet();
mySet.addAll(myMap.keySet());
Iterator mySetIterator = mySet.iterator();
while (mySetIterator.hasNext()) {
Object newObj = mySetIterator.next();
Object mapObj = myMap.get(newObj);
}
此 while
循环仅迭代一次。我不确定这里出了什么问题。有什么问题吗?
请帮我。提前致谢。
更新:
现在我在 mySet.addAll(myMap.keySet());
中遇到以下异常
<Oct 18, 2011 12:36:21 PM IST> <Error> <> <BEA-000000> <java.lang.NullPointerException
at edu.emory.mathcs.backport.java.util.TreeMap.compare(TreeMap.java:934)
at edu.emory.mathcs.backport.java.util.TreeMap.put(TreeMap.java:97)
at edu.emory.mathcs.backport.java.util.TreeSet.add(TreeSet.java:149)
at java.util.AbstractCollection.addAll(AbstractCollection.java:318)
at edu.emory.mathcs.backport.java.util.TreeSet.addAll(TreeSet.java:165)
It is a old code and am debugging it.
I have a Map
(myMap) with size 2 (for sure). Keys are null
and 1
.
SortedSet mySet = new TreeSet();
mySet.addAll(myMap.keySet());
Iterator mySetIterator = mySet.iterator();
while (mySetIterator.hasNext()) {
Object newObj = mySetIterator.next();
Object mapObj = myMap.get(newObj);
}
This while
loop, iterates for only one time. I am not sure what is wrong here. Is there any problem?
Please help me. Thanks in advance.
Update:
Now I am getting below exception in mySet.addAll(myMap.keySet());
<Oct 18, 2011 12:36:21 PM IST> <Error> <> <BEA-000000> <java.lang.NullPointerException
at edu.emory.mathcs.backport.java.util.TreeMap.compare(TreeMap.java:934)
at edu.emory.mathcs.backport.java.util.TreeMap.put(TreeMap.java:97)
at edu.emory.mathcs.backport.java.util.TreeSet.add(TreeSet.java:149)
at java.util.AbstractCollection.addAll(AbstractCollection.java:318)
at edu.emory.mathcs.backport.java.util.TreeSet.addAll(TreeSet.java:165)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请检查关键对象上的compareTo 方法。
如果键对象的compareTo方法表明两个键对象比较相同,则键集将只有一个值,因为Set不允许重复。您正在使用 Treeset 来存储您的键,因此您的compareTo 方法可能存在问题。
请把完整代码贴在上下文中,以便正确定位问题。
Pleas check the compareTo method on the Key Objects.
If the key object compareTo method indicates that both key objects compare the same then the keyset will have only one value as Set does not allow duplicates. You are using Treeset to store your keys ,so there could be a problem in your compareTo Method.
Please post the entire code in the context to locate the problem correctly.
SortedSet
中不可能有null
,因为该集合需要调用comparTo
方法,所以这必须是可比较的对象/基元It is impossible to have
null
inSortedSet
, because this collection need callcomparTo
method, so this must be comparable objects/primitives如果你这样做会发生什么?
What happens if you do this?