这里写自定义目录标题
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:
ClassCastException – if the class of an element of this list is incompatible with the specified collection (optional)
NullPointerException – if 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);
}
- 传入参数不可为空,删除List中含有传入集合的元素。 当List发生变化时,返回true,否则返回false。
- 当List中的元素与传入的List中的元素不匹配时,抛出 ClassCastException类型转换异常。
- 当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进行判空来确定是否取得交集,取得交集则不为空。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/99710.html