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.
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.
Yes, you can always use null instead of an object.
TreeMap sorts elements in natural order and doesn't allow null keys because compareTo() method throws NullPointerException if compared with null.
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.
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+" "); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With