1

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)
Vaandu
  • 4,857
  • 12
  • 49
  • 75
  • 3
    Please provide a short but complete program which demonstrates the problem. – Jon Skeet Oct 14 '11 at 16:19
  • I think you should ask a new question as it is a new issue in order to avoid the confusion. The NPE is coming from compare method in treemap. Do you have a valid comparator for the treeset? Or the class implements comparable with the compareTo method implemented? Are there any null keys? could be your compareTo method also can throw the exception? Please post new code in your new question. – java_mouse Oct 18 '11 at 13:26

3 Answers3

1

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.

java_mouse
  • 2,069
  • 4
  • 21
  • 30
1

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

lukastymo
  • 26,145
  • 14
  • 53
  • 66
0

What happens if you do this?

Iterator mySetIterator = myMap.keySet().iterator();
while (mySetIterator.hasNext()) {
     Object newObj = mySetIterator.next();
     Object mapObj = myMap.get(newObj);
}
Jack Leow
  • 21,945
  • 4
  • 50
  • 55