Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding null to empty TreeSet raising NullPointerException

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....

like image 413
user3516780 Avatar asked Jun 30 '14 11:06

user3516780


1 Answers

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:

like image 184
NilsH Avatar answered Nov 15 '22 18:11

NilsH