These Sets allow null. Why can't I add null elements?

This is why I don't like to rely on auto-boxing. Java Collections cannot store primitives (for that you will need a third party API like Trove). So, really, when you execute code like this:

hashSet.add(2);
hashSet.add(5);

What is really happening is:

hashSet.add(new Integer(2));
hashSet.add(new Integer(5));

Adding a null to the hash set is not the problem, that part works just fine. Your NPE comes later, when you try and unbox your values into a primitive int:

while(it.hasNext()){
    int i = it.next();
    System.out.print(i+" ");
}

When the null value is encountered, the JVM attempts to unbox it into an the int primitive, which leads to an NPE. You should change your code to avoid this:

while(it.hasNext()){
    final Integer i = it.next();
    System.out.print(i+" ");
}

1) Are you sure about you get compile time error? I don't think so, I guess the code throws NPE at runtime at

int i = it.next();

2) As a matter of fact java.util.Set interface does not forbid null elements, and some JCF Set implementations allow null elements too:

Set API - A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.

HashSet API - This class permits the null element.

LinkedHashSet API - This class provides all of the optional Set operations, and permits null elements

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


No, Set Interface do allow null value only its implementation i.e. TreeSet doesn't allow null value.

even though you have not written iteration code and have only oTreeSet.add(null) in your code it compiles and at runtime it throws NullPointerException.

TreeSet class's add() method internally calls put() method of TreeMap class. null value is not allowed as below code in put() method

if (key == null)
     throw new NullPointerException();

Tags:

Java

Null

Hashset