Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

null

hashset

I want to know why HashSet, LinkedHashSet and TreeSet implementation does not allow null elements? Whenever i try to run the following code it throws a null pointer exception.

public static void main(String[] args) {      HashSet<Integer> hashSet = new HashSet<Integer>();      hashSet.add(2);     hashSet.add(5);     hashSet.add(1); //  hashSet.add(null);  will throw null pointer      hashSet.add(999);     hashSet.add(10);     hashSet.add(10);     hashSet.add(11);     hashSet.add(9);     hashSet.add(10);     hashSet.add(000);     hashSet.add(999);     hashSet.add(0);      Iterator<Integer> it = hashSet.iterator();     while(it.hasNext()){         int i = it.next();         System.out.print(i+" ");     }     } 

Please guide me.

like image 385
nakul Avatar asked Feb 08 '13 14:02

nakul


People also ask

Why does HashSet allow null values?

The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time. This class permits the null element.

Can a null value added to a list?

Yes, you can always use null instead of an object.

Why null insertion is not possible in TreeMap?

TreeMap sorts elements in natural order and doesn't allow null keys because compareTo() method throws NullPointerException if compared with null.

How many nulls are allowed in set?

In mathematical sets, the null set, also called the empty set, is the set that does not contain anything. It is symbolized or { }. There is only one null set. This is because there is logically only one way that a set can contain nothing.


1 Answers

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+" "); } 
like image 164
Perception Avatar answered Oct 09 '22 03:10

Perception