这可能是重复的,但我看不到任何与此错误有关的问题,所以如果是重复的,请道歉。
我正在尝试使用 remove()
方法从我的 ArrayList
中删除一个 Integer,但是它给了我 java.lang.UnsupportedOperationException
。根据我的理解,删除方法应该采用 int
或 Integer,或者来自 ArrayList
的值,但是这些似乎不起作用并给出相同的错误。
我还尝试使用“深度”作为索引
,因为这是我想要删除的索引
。
这是我的代码:
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;
}
}
最佳答案
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));
也就是说,请调用 items.remove
从迭代 items
的循环内使用增强的 for 循环将不起作用(它将抛出 CuncurrentModificationException
)。您可以使用传统的 for 循环(如果您想删除 Iterator
指向的当前元素,则可以使用显式 Iterator
,但情况似乎并非如此)。
关于java - ArrayList 删除方法不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37036555/