Java ArrayList retainAll() 方法
示例
從列表中移除不屬於指定集合的項
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
cars.add("Toyota");
ArrayList<String> valid = new ArrayList<String>();
valid.add("Volvo");
valid.add("Ford");
valid.add("Mazda");
cars.retainAll(valid);
System.out.println(cars);
}
}
定義和用法
retainAll()
方法從列表中移除所有不屬於指定集合的項。
語法
public boolean retainAll(Collection items)
引數值
引數 | 描述 |
---|---|
items | 必需。一個包含要保留在列表中的項的集合,所有其他項都將被移除。 |
技術詳情
返回 | 如果列表發生更改,則為 true ,否則為 false 。 |
---|---|
丟擲 |
NullPointerException - 如果集合為 null。 |
相關頁面
❮ ArrayList 方法