簡體   English   中英

簡單的 ArrayList.remove(int) 不起作用。 我做錯了什么?

[英]Simple ArrayList.remove(int) doesn't work. What I am doing wrong?

我正在嘗試遍歷ArrayList並在某些條件下( x == 0 )刪除實際的 object (索引 s)。 如果執行,它總是在應該刪除 object 的行處給出錯誤。 沒有remove()它運行得非常好。

int s = 0;
int x = 0;
if (!objectList.isEmpty()) {
    for (obj actualObj : objectList) {
        if (x == 0) {
            objectList.remove(s);
        } else {
            System.out.println("x != 0");
        }
        s++;
    }
} else {
    System.out.println("list is empty");
}

我最大的挑剔是:當使用增強的 for-each 循環( for (T val: Iterator#remove for (T val: Iterable<T>) )。 事實上, Iterator#remove的存在正是因為這個原因:

int toRemove = 0; //The number to remove from your list
List<Integer> list = /* your list */;
Iterator<Integer> itr = list.iterator(); //Create an iterator of the collection
while (itr.hasNext()) { //while new elements are available...
    Integer val = itr.next(); //grab the next available element
    if (val == toRemove) { //removal condition
        itr.remove(); //remove the last grabbed element from the collection
    }
}

如果您能夠使用 Java 8:

int toRemove = 0; //The number to remove from your list
List<Integer> list = /* your list */;
list.removeIf(val -> toRemove == val); //didn't use member reference, for clarity reasons

每次使用索引從List中刪除一個元素時, List都會縮小,因為隨后的元素會向左/向下移動一個位置。 這意味着在循環的下一次迭代中,您實際上將刪除一個元素,該元素與最后一個刪除元素的下一個元素相鄰。

出於這個原因,您應該在循環中使用Iterator而不是索引從List中刪除元素,如下所示:

Iterator<YourType> itr = objectList.iterator();
while (itr.hasNext()) {
    YourType obj = itr.next();
    if (some condition) {
        itr.remove();
    }
    // ...
}

您在迭代列表時從列表中刪除。 一個可行的選擇是

    int x = 0;
    List<String> objectList = Arrays.asList("A", "B", "C");
    if (objectList.isEmpty()) System.out.println("list is empty");

    List<String> filtered = objectList.stream().filter(s1 -> x != 0).collect(Collectors.toList());
    System.out.println(objectList + "\n" + filtered);

暫無
暫無

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

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