Re: [問題] UnsupportedOperationException?
※ 引述《tkcn (小安)》之銘言:
: ※ 引述《adrianshum (Alien)》之銘言:
: : 與是不是 array 沒關係.
: : 為什麼內部用 array 放就不可以 add remove?
: 舉這個例子是因為 array 不能動態改變 size,
: 所以如果需要 add, remove,
: 就必須像 java.util.ArrayList 那樣偷偷動些手腳。
: 而 Arrays$ArrayList 在操作後,
: 其內容仍然會與原先傳入的 array 相同。 (因為根本是同一個 array)
: 也就是說我可以利用 Arrays.asList() 得到 List 物件後對它進行操作,
: 之後直接存取 array 時就已經是被操作過後的物件,
: 而不需要再用 array = list.toArray()。
: 在不破壞上面這個特性的前提下,
: 如果 Collection 的內部是用 array,
: 那就一定不能 add, remove。
: 這是我當初的那樣說的想法,不過好像不是很重要 :p
你可能搞錯了.
Arrays.asList 的那個 "特性" 是因為那是故意令某 array
能以 collection 的樣子出現, 作為 array 與 collection
之間的橋樑, 所以 Arrays$ArrayList 是會 "write through"
到 array. 換句話說, 那是讓某特定 Array instance 包上
collection 的皮. 由於某特定 array instance 不能改變
length, 所以不能提供 add/remove.
但這個並不是 "Collection 內部是用 array" 的特性.
一般的 ArrayList 並不是要 "展示" 某特定 array.
既然如此就不必執著不能替換內部自用的 array, 所以
沒有不能 add remove 之理.
[43]
: To implement an unmodifiable list, the programmer needs only to extend this
: class and provide implementations for the get(int) and size() methods.
: To implement a modifiable list, the programmer must additionally override
: the set(int, E) method (which otherwise throws an UnsupportedOperationExce-
: ption).
: If the list is variable-size the programmer must additionally override the
: add(int, E) and remove(int) methods.
: 其實 Arrays.ArrayList 有提供 set method,
: 所以他應該是一個 non-variable-size 的 modifiable list。
原來還有這種, 謝謝指教 :)
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 202.155.236.82
推
01/25 16:39, , 1F
01/25 16:39, 1F
→
01/25 19:34, , 2F
01/25 19:34, 2F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 4 之 4 篇):