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
.