Ror*_*llo 0 java methods int integer arraylist
这可能是重复的,但我看不出有任何关于此错误的问题,所以请道歉.
我正在尝试使用该remove()方法从我的移除整数ArrayList,但它给了我java.lang.UnsupportedOperationException.remove方法应该int对我的理解采用一个或整数,或者来自的值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;
}
}
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)
也就是说,items.remove在items使用增强型for循环迭代的循环内调用将不起作用(它将抛出CuncurrentModificationException).你可以使用传统的for循环(Iterator如果你想删除Iterator指向的当前元素,则可以使用显式,这似乎不是这种情况).
| 归档时间: |
|
| 查看次数: |
318 次 |
| 最近记录: |