Adding null to empty TreeSet raising NullPointerException

user3516780 picture user3516780 · Jun 30, 2014 · Viewed 18.1k times · Source
import java.util.TreeSet;
class Test 
{
    public static void main(String[] args) 
    {
        TreeSet t=new TreeSet();
        t.add(null);
        System.out.println(t);
    }
}

output: NullPointerException. I read in many articles that empty TreeSet will accept null for first time but am getting NullPointerException...am using java7..can any body clarify my doubt....

Answer

NilsH picture NilsH · Jun 30, 2014

The documentation for TreeSet#add in Java 7 states:

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

So since you have not specified a custom comparator implementation that can handle null values, you get the NPE.

Edit: It was possible to add a null element as the first element of a TreeSet/TreeMap in Java 6, but it was considered a bug: