簡體   English   中英

如何刪除列表元素

[英]how to remove list element

我正在嘗試刪除列表元素,但出現此異常

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at apollo.exercises.ch08_collections.Ex4_RemoveOdd.removeOdd(Ex4_RemoveOdd.java:25)
at apollo.exercises.ch08_collections.Ex4_RemoveOdd.main(Ex4_RemoveOdd.java:15)

這是我的代碼

public class Ex4_RemoveOdd {
removeOdd(Arrays.asList(1,2,3,5,8,13,21));
removeOdd(Arrays.asList(7,34,2,3,4,62,3));
public static void removeOdd(List<Integer> x){
    for(int i=0;i<=x.size()-1;i++){
        if (x.get(i)%2==0){
            System.out.println(x.get(i));
        }else{
            x.remove(i);
        }
        }
    }
}

所以我做了新的類只是為了嘗試刪除元素

public static void main(String[] args) {
List<Integer> x = Arrays.asList(1,2,3,5,8,13,21);
    x.remove(1);
}

但仍然有錯誤

Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at apollo.exercises.ch08_collections.Ex4_RemoveOdd.main(Ex4_RemoveOdd.java:14)

僅供參考:我試圖解決這個問題https://github.com/thecodepath/intro_java_exercises/blob/master/src/apollo/exercises/ch08_collections/Ex4_RemoveOdd.java

Arrays.asList返回固定大小的列表。 任何試圖修改其大小(通過添加或刪除元素)的調用都將引發此異常。

使用將集合作為參數的ArrayList構造函數。

removeOdd(new ArrayList<>(Arrays.asList(1,2,3,5,8,13,21)));

另外,正如評論中指出的那樣,使用列表的迭代器從其中刪除元素是更安全(強烈建議)。

當前,使用for循環方法將跳過要刪除的元素。 例如,當使用列表[1,2,3,5,8,13,21]調用方法時,第一次迭代將刪除1因此列表中的所有元素都將移動一個。 然后i值為1 ,列表的大小為6list.get(1)將返回3而不是2 ,依此類推。

最后,您會得到[2, 5, 8, 21] ,這不是您想要的。


如果您使用的是 ,則您的代碼可以簡化為

 public static void removeOdd(List<Integer> x){ x.removeIf(i -> i%2 != 0); } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM