繁体   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