Can't I put a null in a SortedSet?

Viewed 8684

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)

4 Answers

You can't insert null values into the TreeSet. From JDK 1.7 onwards null is not accepted into a TreeSet. Insertion of null value into TreeSet will throw NullPointerException reason being while insertion of null, it gets compared to the existing elements and null can't be compared to any value. Till JDK 1.6, the first element insertion can be null but any more null element will result in NullPointerException.

If you have to add null, in that case you have to write your own custom comparator to handle null or either use NullComparator() provided by commons-collections.

Related