Can't I put a zero in a SortedSet?

I thought null allowed for Set .
So why the following code:

 SortedSet<Integer> set = new TreeSet<Integer>(); set.add(null); set.add(1); //--->Line indicated by exception 

Provides the following exception?

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

+7
source share
3 answers

Yes, you can. But you will have to provide your Comparator to handle the case where null compared to any other content in your set. When using natural ordering, Java objects do not know how to compare themselves to null . Conversely, null does not know how to compare itself with any object, since 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 NullComparator . You can 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); 
+16
source

The TreeSet API ( http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html#add (E) ) says add will add NPE:

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

therefore, if you want to keep null, you must provide a Comparator that can handle this, knows where the null value is compared to 0 or all other values.

+5
source

Instead of creating a Comparator, you can create your own "null" value.

 static final Integer NULL = Integer.MIN_VALUE; set.add(NULL): 
+2
source

All Articles