NullPointerException on TreeSet when removeAll ()
From the docs Collection.removeAll()
:
Throws:
NullPointerException
- if this collection contains one or more null elements and the specified collection does not support null (optional), or if the specified collection is null.
But the code below still throws NullPointerException
:
public class TestSet {
public static void main(String[] args) {
Set set1 = new TreeSet();
set1.add("A");
set1.add("B");
Set set2 = new HashSet();
set2.add(null);
set1.removeAll(set2);
}
}
Can anyone help me understand this behavior?
source to share
My guess is that the Javadoc conditions when NullPointerException
can be selected removeAll
are inaccurate.
TreeSet
removeAll
depends on the implementation AbstractSet
. This implementation iterates over all the elements of the smaller of the two sets.
In your snippet HashSet
, that contains the element null
. So, it removeAll
iterates over HashSet
and tries to remove every element it finds from TreeSet
.
However, it is thrown remove
from when you try to remove an item from the set .TreeSet
NullPointerException
null
uses natural ordering, or its comparator does not permit null elements
To summarize, NullPointerException
called TreeSet
remove()
, which is explained in the Javadoc remove()
:
Throws:
ClassCastException - if the specified object cannot be compared with the elements currently in this set
NullPointerException - if the specified element is null and this set uses natural ordering , or its comparator does not allow null elements
It is interesting to note that adding one more element in HashSet
will result in elimination NullPointerException
as in this case both Set
will be the same size and the implementation removeAll()
will iterate over the elements TreeSet
.
source to share
Ok, Nullpointerexception
selected from the remove TreeSet method. Below is the source code of the Treeset methodremoveAll()
public boolean removeAll(Collection<?> c) {
167 boolean modified = false;
168
169 if (size() > c.size()) {
170 for (Iterator<?> i = c.iterator(); i.hasNext(); )
171 modified |= remove(i.next());
172 }
The method removeAll()
calls internally remove()
. Since you are doing some values null
, the TreeSet's remove () method cannot handle it and hence the exception.
NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not allow null elements
source to share