kooyee ‘s blog

          開(kāi)源軟件, 眾人努力的結(jié)晶, 全人類(lèi)的共同財(cái)富
          posts - 103, comments - 55, trackbacks - 0, articles - 66
             :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理
          常常使用Arrays.asLisvt()后調(diào)用add,remove這些method時(shí)出現(xiàn)java.lang.UnsupportedOperationException異常。這是由于:

          Arrays.asLisvt() 返回java.util.Arrays$ArrayList, 而不是ArrayList。Arrays$ArrayList和ArrayList都是繼承AbstractList,remove,add等method在AbstractList中是默認(rèn)throw UnsupportedOperationException而且不作任何操作。ArrayList override這些method來(lái)對(duì)list進(jìn)行操作,但是Arrays$ArrayList沒(méi)有override remove(int),add(int)等,所以throw UnsupportedOperationException。

          解決方法是使用Iterator,或者轉(zhuǎn)換為ArrayList
          List list = Arrays.asList(a[]);
          List arrayList 
          = new ArrayList(list);


          參考

          When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list. You cannot add to it and you cannot remove from it.

          If you want a mutable list built from your array you will have to loop over the array yourself and add each element into the list in turn.

          Even then your code won't work because you'll get an IndexOutOfBoundsException as you remove the elements from the list in the for loop. There are two options: use an Iterator which allows you to remove from the list as you iterate over it (my recommendation as it makes the code easier to maintain) or loop backwards over the loop removing from the last one downwards (harder to read).

          You are using AbstractList. ArrayList and Arrays$ArrayList are both types of AbstractList. That's why you get UnsupportedOperationException: Arrays$ArrayList does not override remove(int) so the method is called on the superclass, AbstractList, which is what is throwing the exception because this method is not implemented on that class (the reason being to allow you to build immutable subclasses).


          評(píng)論

          # re: 『Java』java.lang.UnsupportedOperationException at java.util.AbstractLis[未登錄](méi)  回復(fù)  更多評(píng)論   

          2009-08-15 11:12 by 哈哈
          講解方法很經(jīng)精確
          喜歡這種講解風(fēng)格

          # re: 『Java』java.lang.UnsupportedOperationException at java.util.AbstractLis  回復(fù)  更多評(píng)論   

          2009-09-03 10:02 by javaisgod
          good

          # re: 『Java』java.lang.UnsupportedOperationException at java.util.AbstractLis  回復(fù)  更多評(píng)論   

          2009-09-09 11:55 by kellyzly
          頂,我的問(wèn)題解決了,謝謝

          # re: 『Java』java.lang.UnsupportedOperationException at java.util.AbstractLis  回復(fù)  更多評(píng)論   

          2010-08-18 17:22 by 冬天雞雞好冷
          api 的設(shè)計(jì)多此一舉還搞個(gè)內(nèi)部類(lèi)
          主站蜘蛛池模板: 辽中县| 斗六市| 年辖:市辖区| 若尔盖县| 永吉县| 潮州市| 辽宁省| 孟津县| 安徽省| 叙永县| 洞口县| 荆门市| 姜堰市| 周至县| 盐津县| 庆云县| 五大连池市| 荆门市| 阜城县| 保山市| 灌云县| 措美县| 东山县| 隆子县| 辽宁省| 西城区| 资兴市| 镇雄县| 偏关县| 杨浦区| 日照市| 广汉市| 普兰县| 客服| 丹东市| 涿鹿县| 神池县| 红桥区| 庄河市| 景东| 大荔县|