public static void main(String[] args) {
Collection c1 = new ArrayList();
Collection c2 = new ArrayList();
//添加
c1.add(555);//1.添加一个元素
c1.add(666);
c1.add(777);
c1.add("abc");
c1.add("xyz");
c2.addAll(c1);//2.添加一个集合的元素
System.out.println(c2);
//删除
c1.clear();//1.移除所有的元素
boolean b1 = c2.remove(555);//2.移除一个元素
System.out.print(c2);
System.out.println(" remove555 "+b1);
//3.移除一个集合的元素,只要一个元素被移除了,就返回true
boolean b2 = c2.removeAll(c2);
System.out.println(c2+" removeAll "+b2);
//判断
Collection c3 = new ArrayList();
c3.add(555);
c3.add("abc");
c3.add("yyy");
//1.判断集合是否包含该元素
boolean b3 = c3.contains(555);
//2.判断集合中是否包含指定的集合元素
boolean b4 = c3.containsAll(c2);
System.out.println("contains "+b3);
System.out.println("containsAll "+b4);
//3.判断集合是否为空
boolean b5 = c2.isEmpty();
System.out.println("isEmpty " + b5);
//迭代器 (遍历集合)
/*
* Iterator有三个方法:hasnext()、next()、remove()、
* hasnext()没有指针下移,只是判断是否存在下一个元素
* next()指针下移,返回该指针指向的元素
* remove删除当前指针指向的元素,一般和next方法一起用,
* 其作用是删除next方法返回的元素
*/
Iterator it = c3.iterator();
//1.while遍历
System.out.println("---两种遍历---");
while(it.hasNext()) {
Object obj = it.next();
System.out.print(obj + " ");
if(obj.equals(555)) {
it.remove();//删除
}
}System.out.println();
//2.增强for
for (Object obj : c3) {
System.out.print(obj + " ");
}System.out.println();
//交集
//1.将两个集合的交集给c1,返回值表示c1是否变化
boolean b6 = c1.retainAll(c3);
System.out.println("retainAll " + b6);
System.out.println("c1 " + c1);
System.out.println("c3 " + c3);
}
08-05