阿里巴巴手册之-Arrays.asList()数组转集合的问题

转载来源:https://blog.csdn.net/qq_36443497/article/details/79663663?utm_source=blogxgwz9

在使用工具类Arrays.asList()把数组转换成集合时,不能使用其修改集合的相关方法,他的add/remove/clear方法都会抛出UnsupportedOperationException异常。

说明:

    asList的返回对象是一个Arrays的内部类,并没有实现集合的修改方法。Arrays.asList体现的是适配器模式,只是转换接口,后台的数据仍然是数组。

  String[] str = new String[]{"you", "me"};

  List list = Arrays.asList(str);

其中第一种情况:list.add("thanks");会报运行时异常。

第二种情况:如果str[0] = "ganma"; ,那么list.get(0);也会随之改变;

较为实用的正确转化为集合并可以使用集合方法的转化方式:
第一:

List<Integer> list = new ArrayList<Integer>(Arrays.asList(1,2,5,4,3));

    即使用另外的Collection来将自身初始化。

第二:

 Colllection<Integer> collection = new ArrayList<Integer>();

 Integer[] moreInts = {6,8,4,5,8,4};

 Collections.addAll(collection,moreInts);

 Collections.addAll(collection,1,5,4,7,8,4,1);

第三:

collection.addAll(Arrays.asList(moreints));

在Java编程思想第四版中表示这三种由上到下为常用较为使用的转化方式。

其中collection.addAll()成员方法只接受另一个Collection对象作为参数,因此他不如asList和Collections.addAll()灵活,因为他们都可以接受可变参数列表。

猜你喜欢

转载自www.cnblogs.com/bbllw/p/10080152.html