- 添加数据
import java.util.ArrayList;
import java.util.Collection;
public class Demo3 {
public static void main(String[] args) {
Collection col1 = new ArrayList<>();
Collection col2 = new ArrayList<>();
//1.添加数据
col1.add(10);
col1.add(new String("hello"));
col2.addAll(col1);
System.out.println(col1);
System.out.println(col2);
}
}
运行结果:
- 删除元素
//2.删除
col1.remove(10);
运行结果:
//删除与col2集合中相同的元素
col1.removeAll(col2);
运行结果:
//删除与col2集合中不相同的元素,如果有删除则返回true
boolean retainAll = col1.retainAll(col2);
运行结果:
//删除与col2集合中不相同的元素,如果有删除则返回true
boolean retainAll = col2.retainAll(col1);
System.out.println(col1);
System.out.println(col2);
System.out.println(retainAll);
运行结果:
- 清空
//清空
col1.clear();
运行结果:
- 查询
//查询
//查询集合中元素的个数
int size = col1.size();
System.out.println(size);
//查询(打印)集合中所有的元素
System.out.println(col1);
运行结果:
- contains
//4.contains:查询集合中是否包含某个元素
boolean contains = col1.contains("hello");
System.out.println(contains);
运行结果:
boolean containsAll = col1.containsAll(col2);
System.out.println(containsAll);
运行结果: