从文档Collection.removeAll() https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#removeAll(java.util.Collection):
Throws: NullPointerException
- 如果该集合包含一个或多个
null 元素且指定集合不支持
null 元素(可选),或者指定的集合是否为 null。
但下面的代码仍然抛出一个NullPointerException https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html:
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);
}
}
有人可以帮助我理解这种行为吗?
我猜 Javadoc 的条件是什么时候NullPointerException
可能会被抛出removeAll
不准确。
TreeSet
's removeAll
依靠AbstractSet
的实施。该实现迭代两个集合中较小集合的所有元素。
在你的代码片段中,这就是HashSet
,其中包含null
元素。所以removeAll
迭代HashSet
并尝试删除它找到的每个元素TreeSet
.
然而,remove
of TreeSet
抛出一个NullPointerException
当尝试删除一个null
集合中的元素uses natural ordering, or its comparator does not permit null elements
.
总而言之,NullPointerException
是由TreeSet
's remove()
,在 Javadoc 中对此进行了解释remove()
:
Throws:
ClassCastException - 如果指定的对象无法与当前在此集合中的元素进行比较
空指针异常 -如果指定的元素为 null 并且该集合使用自然排序,或其比较器不允许 null 元素
有趣的是,向HashSet
将消除NullPointerException
,因为在这种情况下两者Set
s 将具有相同的大小,并且执行removeAll()
会迭代的元素TreeSet
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)