List和Set中忽略的方法addAll(Collection c)和retainAll(Collection c)

List、Set中都有方法

addAll(Collection c) :
    对于set来说,是将c中所有元素添加到一个Set中,如果Set中已有某一元素,则不添加,因Set不允许有重复值
    对于List来说,是将c中元素append到一个List中
     //Appends all of the elements in the specified collection to the end of this list

retainAll(Collection c)
    两个集合求交集,只保留交集数据 
     //Retains(保留) only the elements in this list that are contained in the specified collection

 

Java代码   收藏代码
  1. String[] ss = {"s1","s2","1"};  
  2.         List str = Arrays.asList(ss);  
  3.           
  4.         List stList = new ArrayList();  
  5.         stList.add("1");  
  6.         stList.add("2");  
  7.         stList.add("3");  
  8.         stList.addAll(str);  
  9.         System.out.println(stList);  
  10.             //结果:[1, 2, 3, s1, s2, 1] 因List中允许重复值  
  11.           
  12.         Set s = new HashSet();  
  13.         s.add("1");  
  14.         //s.add(1);  
  15.         s.add("2");  
  16.         s.add("3");  
  17.         s.addAll(str);  
  18.         System.out.println(s);  
  19.            //结果:[3, 2, s2, 1, s1] 因Set中不允许重复值  
  20.             //若为s.add(1) ,数组ss不变,则结果为:[3, 2, 1, 1, s2, s1] 因其中两个1类型不同  
 
Java代码   收藏代码
  1. List lt1 = new ArrayList();  
  2.         lt1.add("a");  
  3.         lt1.add("b");  
  4.         lt1.add("c");  
  5.         List lt2 = new ArrayList();  
  6.         lt2.add("b");  
  7.         lt2.add("d");  
  8.         lt2.add("f");  
  9.           
  10.         List lt3 = new ArrayList();  
  11.         lt3.addAll(lt1);  
  12.         lt3.retainAll(lt2);  
  13.         System.out.println(lt3);  
  14.             //结果:[b]  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值