简体   繁体   English

简单的 ArrayList.remove(int) 不起作用。 我做错了什么?

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

I am trying to iterate through an ArrayList and remove the actual object (index s) under certain conditions ( x == 0 ).我正在尝试遍历ArrayList并在某些条件下( x == 0 )删除实际的 object (索引 s)。 It always gives an error at the line where the object should be removed, if executed.如果执行,它总是在应该删除 object 的行处给出错误。 Without the remove() it runs perfectly fine.没有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");
}

My biggest nitpick would be this: you can't mutate/modify the collection you are iterating over (outside of calling Iterator#remove , etc) when using syntactic sugar like the enhanced for-each loop ( for (T val: Iterable<T>) ).我最大的挑剔是:当使用增强的 for-each 循环( for (T val: Iterator#remove for (T val: Iterable<T>) )。 In fact, Iterator#remove exists pretty much exactly for this reason:事实上, 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
    }
}

If you're capable of using Java 8:如果您能够使用 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

Each time you remove an element from a List using an index, the List shrinks because the succeeding elements shift one place left/down.每次使用索引从List中删除一个元素时, List都会缩小,因为随后的元素会向左/向下移动一个位置。 It means that in the next iteration of the loop, you will be actually deleting an element which was next to the next of the last deleted element.这意味着在循环的下一次迭代中,您实际上将删除一个元素,该元素与最后一个删除元素的下一个元素相邻。

For this reason, you should delete elements from a List in a loop using an Iterator instead of the index as shown below:出于这个原因,您应该在循环中使用Iterator而不是索引从List中删除元素,如下所示:

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

you are removing from the list while iterating through it.您在迭代列表时从列表中删除。 A workable option is一个可行的选择是

    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.

相关问题 JSF 2.2表单上的tagmanager.js不起作用。 我究竟做错了什么? - tagmanager.js on JSF 2.2 form doesn't work. What am I doing wrong? 使用.add进行arraylist似乎不起作用,我做错了什么? - Using .add for arraylist doesn't seem to work, what am I doing wrong? 简单的加密/解密似乎无法正常工作,请帮助我找到我做错的事情 - Simple encryptio/decryption doesn't seems to work, help me find what i am doing wrong ArrayList.remove(i)不会删除所有对象 - ArrayList.remove(i) doesn't delete all objects as it should 规范化迭代计数不起作用。 我究竟做错了什么? - Normalized Iteration Count does not work. What am I doing wrong? 我在这个ArrayList中做错了什么? - What am I doing wrong in this ArrayList? Java:Paint应用程序,代码不起作用,我在做什么错? - Java: Paint application, the code doesn't work, what am I doing wrong? 官方 Java 练习解决方案不起作用……我做错了什么? - Official Java excercize solution doesn't work… what I am doing wrong? ArrayList.remove(int)与ArrayList.remove(Object)在不同的线程中 - ArrayList.remove(int) vs ArrayList.remove(Object) in different thread 适配器上的arraylist.remove()删除ListView中的错误项目 - arraylist.remove() on adapter deletes wrong item in ListView
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM