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);
Lukas Eder
source share