作者adrianshum (Alien)
看板java
标题Re: [问题] UnsupportedOperationException?
时间Mon Jan 25 16:33:07 2010
※ 引述《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
1F:推 tkcn:谢谢前辈指点 01/25 16:39
2F:→ adrianshum:不要叫我前辈啦 =_= 01/25 19:34