Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't I put a null in a SortedSet?

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)

like image 300
Cratylus Avatar asked Jul 23 '12 07:07

Cratylus


2 Answers

Yes, you can. But you will have to provide your own Comparator to handle the case when null is compared to any other contents of your 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 you 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. You could use it as such:

// Unfortunately no support for Java generics yet, in commons-collections
@SuppressWarnings("unchecked")
SortedSet<Integer> set = new TreeSet<Integer>(new NullComparator());  
set.add(null);  
set.add(1);
like image 82
Lukas Eder Avatar answered Oct 28 '22 16:10

Lukas Eder


the API of TreeSet (http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html#add(E)) says that add will throw a NPE:

if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

so if you want to store null you have to provide a Comparator which can deal with this an knows where null stands compared to 0 or all other values.

like image 37
Korgen Avatar answered Oct 28 '22 17:10

Korgen