集合类父接口中方法的使用介绍 以及不可修改长度与不可修改的两个集合介绍

/**

* Created by likai on 2018/11/29.

* 集合类父接口中方法的使用介绍 以及不可修改长度与不可修改的两个集合介绍

*/

public class Test1 {

public static void test(String msg, List<String> list) {

System.out.println("----------"+msg+"------------");

 

Collection<String> c = list ;

 

Collection<String> subList = list.subList(1,8) ;

 

Collection<String> c2 = new ArrayList<>(subList) ;

try{

c.retainAll(c2) ;

} catch (Exception e) {

System.out.println("retainAll: " + e);

}

 

try{

c.removeAll(c2) ;

} catch (Exception e) {

System.out.println("removeAll: " + e);

}

 

try{

c.clear(); ;

} catch (Exception e) {

System.out.println("clear: " + e);

}

 

 

try{

c.add("X") ;

} catch (Exception e) {

System.out.println("add: " + e);

}

 

try{

c.addAll(c2) ;

} catch (Exception e) {

System.out.println("addAll: " + e);

}

 

try{

c.remove("C") ;

} catch (Exception e) {

System.out.println("remove: " + e);

}

 

try{

list.set(0,"X") ;

} catch (Exception e) {

System.out.println("list.set: " + e);

}

}

 

public static void main(String [] args) {

 

//Arrays.asList 会生成一个固定大小的集合 因此仅支持那些不会改变集合大小的操作 否则会出现UnsupportedOperationException

List<String> list = Arrays.asList("A B C D E F G H I J K L M N O".split(" ")) ;

 

System.out.println(list.getClass());

 

test("Modifiable Copy",new ArrayList<String>(list));

 

test("Arrays.asList",list) ;

 

//Collections.unmodifiableList 返回一个不可做任何修改的集合

test("unmodifiableLlist()",Collections.unmodifiableList(new ArrayList(list))) ;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值