Map.keySet() and Set.addAll throwing NullPoniterException

1.7k views Asked by At

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)
3

There are 3 answers

1
java_mouse On BEST ANSWER

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.

2
lukastymo On

It is impossible to have null in SortedSet, because this collection need call comparTo method, so this must be comparable objects/primitives

0
Jack Leow On

What happens if you do this?

Iterator mySetIterator = myMap.keySet().iterator();
while (mySetIterator.hasNext()) {
     Object newObj = mySetIterator.next();
     Object mapObj = myMap.get(newObj);
}