您的位置:首页 > 其它

16-集合框架-04-常用对象API(集合框架-方法演示_2)

2015-08-11 09:27 459 查看
package cn.itacst.collection.demo;

import java.util.ArrayList;
import java.util.Collection;

public class CollectionDemo2 {

public static void main(String[] args) {

Collection c1 = new ArrayList();
Collection c2 = new ArrayList();
show(c1, c2);
}

public static void show(Collection c1, Collection c2) {

// 给c1添加元素
c1.add("abc1");
c1.add("abc2");
c1.add("abc3");
c1.add("abc4");

// 给c2添加元素
c2.add("abc2");
c2.add("abc6");
c2.add("abc7");

System.out.println("c1:" + c1);// c1:[abc1, abc2, abc3, abc4]
System.out.println("c2:" + c2);// c2:[abc2, abc6, abc7]

// 演示addAll
c1.addAll(c2);// 将c2中的所有元素添加到c1中
System.out.println("c1:" + c1);// c1:[abc1, abc2, abc3, abc4, abc2, abc6, abc7]

// 演示removeAll
boolean b = c1.removeAll(c2);
System.out.println("removeAll:"+b);//removeAll:true
System.out.println("c1:" + c1);//c1:[abc1, abc3, abc4]
//发现removeAll作用是将两个集合中相同元素从调用该方法的集合中删除

//演示containsAll
boolean b1 = c1.containsAll(c2);
System.out.println("b1:"+b1);//false,因为c2内有abc2、abc6、abc7,而c1中不包含abc6和abc7
//只有当c2是c1的子集,containsAll才返回真

//演示retainAll
c1.add("abc1");
c1.add("abc2");
c1.add("abc3");
c1.add("abc4");

c2.add("abc2");
c2.add("abc6");
c2.add("abc7");

boolean b2 = c1.retainAll(c2);//将c1和c2的交集放入c1中
System.out.println("c1:"+c1);//c1:[abc2]
//发现removeAll和retainAll正好相反,前者是将两个集合中相同的元素在调用该方法的集合中干掉,而后者是保留二者交集存入调用该方法的集合中
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: