1. 程式人生 > >阿里巴巴手冊之-Arrays.asList()陣列轉集合的問題

阿里巴巴手冊之-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()靈活,因為他們都可以接受可變引數列表。