zoukankan      html  css  js  c++  java
  • 阿里巴巴手册之-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()灵活,因为他们都可以接受可变参数列表。

  • 相关阅读:
    牛客 动物园 (KMP)
    网络流模板与经典模型
    Codeforces Round #698 (Div. 2)
    CF1485X Codeforces Round #701
    CF1479B Painting the Array(贪心+DP)
    「AGC021E」Ball Eat Chameleons
    「AGC034E」 Complete Compress
    「AGC034D」 Manhattan Max Matching
    「ARC103D」 Distance Sums
    「AGC035C」 Skolem XOR Tree
  • 原文地址:https://www.cnblogs.com/bbllw/p/10080152.html
Copyright © 2011-2022 走看看