簡體   English   中英

ArrayList刪除方法不起作用?

[英]ArrayList remove method not working?

這可能是重復的,但我看不到與此錯誤有關的任何問題,因此請諒解。

我正在嘗試使用remove()方法從ArrayList刪除一個Integer,但是它給了我java.lang.UnsupportedOperationException 據我所知,remove方法應該采用int或Integer或ArrayList的值,但是這些似乎不起作用並且給出相同的錯誤。

我也嘗試過使用“ depth”作為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;
}
}

Arrays.asList返回的List實現不是java.util.ArrayList 這是在Arrays類內部定義的不同實現,該類是固定大小的List 因此,您不能在該List添加/刪除元素。

您可以通過創建一個新的java.util.ArrayList來克服此問題,該ListList的元素初始化:

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

就是說,從使用增強的for循環迭代items的循環內調用items.remove將不起作用(它將拋出CuncurrentModificationException )。 您可以改用傳統的for循環(如果要刪除Iterator指向的當前元素,則可以使用顯式Iterator ,似乎並非如此)。

暫無
暫無

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

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