Wednesday, July 16, 2014

null in Sortedset

We think that null is allowed for a Set.
So why does the following code:
SortedSet<Integer> set = new TreeSet<Integer>(); 
set.add(null); 
set.add(1);  //--->Line indicated by exception 
Gives the following exception?

Exception in thread "main" java.lang.NullPointerException at
java.lang.Integer.compareTo(Unknown Source) at
java.lang.Integer.compareTo(Unknown Source) at
java.util.TreeMap.put(Unknown Source) at
java.util.TreeSet.add(Unknown Source)


Yes, we can use null. But we will have to provide our own Comparator to handle the case when null is compared to any other contents of our set.


With natural ordering applied, Java objects do not know how to compare themselves to null.
Inversely, null doesn't know how to compare itself with any object as we cannot call null.compareTo(object).


An example implementation of such a "null-safe" Comparator can be found in the apache commons-collections library. Check out the NullComparator. We could use it as such:

@SuppressWarnings("unchecked")
SortedSet<Integer> set = new TreeSet<Integer>(new NullComparator());  
set.add(null);  
set.add(1);


No comments:

Post a Comment