抛出:
NullPointerException-如果该集合包含一个或多个空元素,而指定的集合不支持空元素(可选),或者指定的集合为空。
但是下面的代码仍然会抛出一个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);
}
} 有人能帮我理解这种行为吗?
发布于 2017-06-15 10:13:33
我想Javadoc关于何时NullPointerException可能被removeAll抛出的条件是不准确的。
TreeSet的removeAll依赖于AbstractSet的实现,该实现迭代了两个集合中较小的元素。
在您的代码段中,这是HashSet,它包含null元素。因此,removeAll遍历HashSet并尝试删除它从TreeSet中找到的每个元素。
但是,remove of TreeSet在尝试从null元素中删除null元素时抛出一个uses natural ordering, or its comparator does not permit null elements。
总之,NullPointerException是由TreeSet的remove()引起的,这在remove()的Javadoc中得到了解释。
抛出: ClassCastException -如果指定的对象不能与此集合中当前的元素进行比较 NullPointerException -如果指定的元素为空,且此集合使用自然排序,或者其比较器不允许空元素。
值得注意的是,向HashSet再添加一个元素将消除NullPointerException,因为在本例中,两个Set的大小相同,而removeAll()的实现将迭代TreeSet的元素。
发布于 2017-07-19 06:03:52
好的,从TreeSet的remove方法抛出的TreeSet。下面是Treeset的removeAll()方法的源代码
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 }removeAll()方法内部调用remove() .Since,您使用的是一些null值,TreeSet的remove()方法无法处理它,因此出现了异常。
NullPointerException -如果指定的元素为空,且此集合使用自然排序,或者其比较器不允许空元素。
https://stackoverflow.com/questions/44564757
复制相似问题