[精讚] [會員登入]
534

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

你可能感興趣的文章

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

停止多執行緒 利用主程式呼叫多執行緒時, 要怎麼停止正在執行的多執行緒

spring boot jpa 使用多個欄位排序 我有一entity 叫 team 資料欄下如下 @Id @GeneratedValue(strategy = Gener

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

spring boot 使用jdbc連接mariadb spring boot, mariadb, jdbc, rowmapper

Spring Boot Maven wrappers maven, mvnw, build command

隨機好文

[vue.js] 動態的props 做parent-child components 雙向綁定 vue.js props components camel-case

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

vim 特定範圍行數開頭加上# 註解 vim 特定範圍行數開頭加上# 註解

雲端校務系統與OPENLDAP帳號整合(2) openldap,雲端校務

scratch 不重覆隨機取陣列值 隨機取數是在設計遊戲時, 很常用到的技巧 最簡單的就是使用運算積木裡的隨機取數範圍 但是, 如果我是想全部取出且不重覆,