ArrayList删除方法不起作用?

时间:2016-05-04 19:37:32

标签: java arraylist methods integer int

这可能是重复的,但我看不出有任何关于此错误的问题,所以道歉是否是。

我正在尝试使用remove()方法从我的ArrayList中移除整数,但它会给我java.lang.UnsupportedOperationException。 remove方法应该根据我的理解采用int或Integer,或ArrayList中的值,但这些似乎不起作用并给出相同的错误。

我也尝试使用“深度”作为index,因为那是我想删除的index

这是我的代码:

import java.util.*;

public class EP{
public static List<Integer> items = Arrays.asList(12, 13, 48, 42, 38,     2827, 827, 828, 420);
public static void main(String[]args){
System.out.println("Exam List");
for(Integer i: items){
    System.out.println(i);
}
    Scanner scan = new Scanner(System.in);
System.out.println("Enter depth");
int depth = scan.nextInt();
System.out.println("Enter value");
int value = scan.nextInt();
System.out.println(mark(depth, value));
}

public static int  mark(int depth, int value){
int ret = -1; //This ensures -1 is returned if it cannot find it at the specified place
for(Integer i: items){
    if(items.get(depth) == (Integer)value){ //This assummes depth starts at 0
    ret = value;
    items.remove(items.get(depth)); // has UnsupportedOperationException
    }
    }
System.out.println("Updated Exam List");
for(Integer j: items){
    System.out.println(j);
}
return ret;
}
}

1 个答案:

答案 0 :(得分:8)

List返回的Arrays.asList实施不是java.util.ArrayList。它是Arrays类中定义的不同实现,它是固定大小的List。因此,您无法在List添加/删除元素。

您可以通过创建由java.util.ArrayList的元素初始化的新List来解决此问题:

public static List<Integer> items = new ArrayList<>(Arrays.asList(12, 13, 48, 42, 38, 2827, 827, 828, 420));

也就是说,在使用增强型for循环迭代items.remove的循环内调用items将不起作用(它将抛出CuncurrentModificationException)。您可以使用传统的for循环(如果要删除Iterator指向的当前元素,则使用显式Iterator,这似乎并非如此)。< / p>

相关问题