当 removeAll() 时 TreeSet 中的 NullPointerException [英] NullPointerException in TreeSet when removeAll()

查看:70
本文介绍了当 removeAll() 时 TreeSet 中的 NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Collection.removeAll():

抛出: NullPointerException - 如果此集合包含一个或多个null 元素和指定的集合不支持null 元素(可选),或者如果指定的集合为 null.

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.

但下面的代码仍然抛出一个NullPointerException:

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?

推荐答案

我猜 Javadoc 对于 NullPointerException 何时可能被 removeAll 抛出的条件是不准确的.

I guess that Javadoc's conditions for when NullPointerException may be thrown by removeAll are inaccurate.

TreeSetremoveAll 依赖于 AbstractSet 的实现.该实现迭代了两个集合中较小者的所有元素.

TreeSet's removeAll relies on AbstractSet's implementation. That implementation iterates over all the elements of the smaller of the two sets.

在您的代码段中,这是包含 null 元素的 HashSet.所以 removeAll 遍历 HashSet 并尝试从 TreeSet 中删除它找到的每个元素.

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.

但是,当尝试从集合中删除 null 元素时,TreeSetremove 会抛出 NullPointerException使用自然排序,或者它的比较器不允许空元素.

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.

总而言之,NullPointerException 是由 TreeSetremove() 引起的,这在 remove 的 Javadoc 中有解释():

To summarize, the NullPointerException is caused by TreeSet's remove(), which is explained in the Javadoc of remove():

投掷:

ClassCastException - 如果指定的对象不能与当前在这个集合中的元素进行比较

ClassCastException - if the specified object cannot be compared with the elements currently in this set

NullPointerException - 如果指定的元素为 null 并且此集合使用自然顺序,或者其比较器不允许 null 元素

NullPointerException - if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements

有趣的是,向 HashSet 添加一个元素将消除 NullPointerException,因为在这种情况下,两个 Set 都会有相同的大小,并且 removeAll() 的实现将遍历 TreeSet 的元素.

It's interesting to note that adding one more element to the HashSet would eliminate the NullPointerException, since in this case both Sets would have the same size, and the implementation of removeAll() would iterate over the elements of the TreeSet.

这篇关于当 removeAll() 时 TreeSet 中的 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆