[精讚] [會員登入]
569

Arrays.asList 後想再add出現 UnsupportedOperationException

這個問題真是搞死我了 List<String> fruits = Arrays.asList("a

分享此文連結 //n.sfs.tw/13240

分享連結 Arrays.asList 後想再add出現 UnsupportedOperationException@igogo
(文章歡迎轉載,務必尊重版權註明連結來源)
2019-10-24 09:17:23 最後編修
2019-04-10 20:42:41 By igogo
 

 

這個問題真是搞死我了

 

 List<String> fruits = Arrays.asList("apple", "orange");
 fruits.forEach(fruit-> System.out.println(fruit));

原本這樣過得好好的,誰知客人想再多點

所以我很直覺的操作

fruits.add("water");

杯具就發生了

Caused by: java.lang.UnsupportedOperationException: null

搞了半天, 才看到這一句, 上網查了一下

原來是Arrays.asList() 回傳是固定值  不能再增刪

https://stackoverflow.com/questions/30174623/arrays-aslist-give-unsupportedoperationexception

但是客人喜歡怎麼辦? 改這樣處理

List<String> fruits = new ArrayList<>();
Arrays.asList("apple", "orange").forEach(fruit->fruits.add(fruit));
fruits.add("water");

fruits.forEach(fruit-> System.out.println(fruit));

 

END

你可能感興趣的文章

ArrayList 與 HashMap 範例 public static void main(String[] args) { String titleIds = &

使用poi 解析 docx 原先是想解析出在docx 中的文字跟圖片, 但是, 有些我們認為是圖片, 其實是用方程式表示, 實在是太麻煩了 就記錄一

[vue.js] 設定 content type 今天在wickt 端怎麼就是收不到vue.js 以post 傳過來的資料 找了好久才發現 application/jso

利用maven建立一個可執行的jar檔 利用maven建立一個可執行的jar檔

Thread java thread

Spring Boot Maven wrappers maven, mvnw, build command

隨機好文

[vue.js] input event Form-Input-Components-using-Custom-Events

axios vuejs application/x-www-form-urlencoded 送資料 VUE.JS 以 application/x-www-form-urlencoded 送資料

找尋多個文件夾中最新檔案(jpg,png,txt)並複製到nexus資料夾 找尋多個文件夾中最新檔案(jpg,png,txt)並複製到集中資料夾

ArrayList 與 HashMap 範例 public static void main(String[] args) { String titleIds = &

在docker裡跑spring boot+mongo(一) 系統安裝docker ce centos7 + docker ce https://docs.docker.com/in