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+" ");
}