Reputation: 11156
From the docs of Collection.removeAll()
:
Throws:
NullPointerException
- if this collection contains one or more null elements and the specified collection does not support null elements (optional), or if the specified collection is null.
But the code below does still throw a 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 someone help me understand this behavior?
Upvotes: 3
Views: 1567
Reputation: 121998
Ok, the Nullpointerexception
thrown from remove method of TreeSet. Below is the source code of Treeset's removeAll()
method
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 removeAll()
method internally calling remove()
.Since you are performing with some null
values , TreeSet's remove() method can't process it and hence the exception.
NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements
Upvotes: 2
Reputation: 393821
I guess that Javadoc's conditions for when NullPointerException
may be thrown by removeAll
are inaccurate.
TreeSet
's removeAll
relies on AbstractSet
's implementation. That implementation iterates over all the elements of the smaller of the two sets.
In your snippet, that's the HashSet
, which contains the null
element. So removeAll
iterates over the HashSet
and attempts to remove each element it finds from the TreeSet
.
However, remove
of TreeSet
throws a NullPointerException
when trying to remove a null
element from as set that uses natural ordering, or its comparator does not permit null elements
.
To summarize, the NullPointerException
is caused by TreeSet
's remove()
, which is explained in the Javadoc of 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 permit null elements
It's interesting to note that adding one more element to the HashSet
would eliminate the NullPointerException
, since in this case both Set
s would have the same size, and the implementation of removeAll()
would iterate over the elements of the TreeSet
.
Upvotes: 4