I thought 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, you can. But you will have to provide your own
Comparatorto handle the case whennullis compared to any other contents of your set. With natural ordering applied, Java objects do not know how to compare themselves tonull. Inversely,nulldoesn’t know how to compare itself with any object as you cannot callnull.compareTo(object).An example implementation of such a “null-safe”
Comparatorcan be found in the apache commons-collections library. Check out theNullComparator. You could use it as such: