一、retainAll(Collection<?> c)
boolean retainAll(Collection<?> c);
1、作用
从当前集合中移除所有不在指定集合 c
中的元素。用于保留两个集合的交集。
2、注意
-
retainAll
会修改原始集合(这里是list1
),慎用! -
判断依据是
.equals()
方法,自定义类需重写 equals 和 hashCode 方法。 -
如果
retainAll
的参数是一个空集合,则原集合会被清空。 -
对于
ArrayList
、LinkedList
、HashSet
、TreeSet
等都适用,因为这个方法定义在Collection
接口中。
3、demo
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> list1 = new ArrayList<>(Arrays.asList("A", "B", "C", "D"));
List<String> list2 = new ArrayList<>(Arrays.asList("B", "C", "E"));
boolean changed = list1.retainAll(list2);
System.out.println("是否发生改变: " + changed); // true
System.out.println("交集结果: " + list1); // [B, C]
}
}