[精讚] [會員登入]
582

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

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

讀取特定資料夾下的xls檔 讀取特定資料夾下的xls檔

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

隨機好文

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

download a file from spring boot controllers ownload a file from spring boot controllers

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

python 的RE python re

hoc2018灑水機器人 灑水機器人的工作是替行道樹灑水,機器人的灑水範圍有限(左前方、左方、左後方),請寫程式控制機器 人判斷須灑水的狀況。每顆