Java中retainAll方法使用

这里写自定义目录标题


retainAll(),接口中的一个方法,ArrayList有对其实现。取交集后有变化返回ture,无变化返回false;没有交集时原集合变为空集合[]

Removes from this list all of its elements that are contained in the specified collection.
Params:
c – collection containing elements to be removed from this list
Returns:
true if this list changed as a result of the call
Throws:
ClassCastExceptionif the class of an element of this list is incompatible with the specified collection (optional)
NullPointerExceptionif this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null
See Also:
Collection.contains(Object)
    public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }
  1. 传入参数不可为空,删除List中含有传入集合的元素。 当List发生变化时,返回true,否则返回false。
  2. 当List中的元素与传入的List中的元素不匹配时,抛出 ClassCastException类型转换异常。
  3. 当List含有null元素并且传入的集合不允许有null元素时,抛出NullPointerException空指针异常;传入集合为空时也抛出空指针异常。

代码及执行结果

List<String> strings = new ArrayList<String>(){{
            add("a1");
            add("b2");
            add("c3");

        }};
        System.out.println("strings = " + strings);

        List<String> retainTrue = new ArrayList<String>(){{
            add("a1");
            add("c3");
            add("e5");
        }};
        System.out.println("retainTrue = " + retainTrue);

        // 取交集后有变化返回ture,无变化返回false;没有交集时原集合变为空集合[]
        boolean changed = retainTrue.retainAll(strings);
        System.out.println(changed);
        System.out.println(retainTrue);

        List<String> retainFalse = new ArrayList<String>(){{
            add("c3");
        }};
        boolean noChanged = retainFalse.retainAll(strings);
        System.out.println(noChanged);
        System.out.println("retainFalse = " + retainFalse);

        List<String> retainEmpty = new ArrayList<String>(){{
            add("d4");
            add("e5");
            add("f6");
        }};
        boolean emptyChanged = retainEmpty.retainAll(strings);
        System.out.println(emptyChanged);
        System.out.println("retainEmpty = " + retainEmpty);
strings = [a1, b2, c3]
retainTrue = [a1, c3, e5]
true
[a1, c3]
false
retainFalse = [c3]
true
retainEmpty = []

注意:retainAll()方法的返回值不可作为判断是否有交集的依据,只是判断原List在调用retainAll()方法后,是否有变化而已。可以对原List进行判空来确定是否取得交集,取得交集则不为空。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值