如何删除列表元素

时间:2014-05-04 14:25:43

标签: java list

我正在尝试删除列表元素但得到此例外

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

1 个答案:

答案 0 :(得分:4)

Arrays.asList返回固定大小的列表。任何试图修改其大小的调用(通过添加或删除元素)都会抛出此异常。

使用以集合作为参数的ArrayList构造函数。

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

同样如评论中所述,使用List的迭代器从中删除元素更安全(并且强烈推荐)。

目前使用for-loop方法,您将跳过要删除的元素。例如,当使用列表[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);
}
相关问题