Java 为什么 ArrayList.remove 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19461632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:27:13  来源:igfitidea点击:

Why ArrayList.remove is not working

javaarraylist

提问by CodeCrypt

I have following code-

我有以下代码-

import java.util.ArrayList;

public class ArrayListExp{
    public static void main (String[] args){

        ArrayList<String> name = new ArrayList<String>();

        name.add("Chris");
        name.add("Lois");
        name.add("Meg");
        name.add("Meg");
        name.add("Brain");
        name.add("Peter");
        name.add("Stewie");

        System.out.println(name);

        for ( int i = 0;  i < name.size(); i++){
            String oldName = name.get(i);
            if(oldName.equals("Meg"))
            {
                name.remove(i);
            }
        }

        System.out.println(name);
    }
}

But here it gives me output -

但在这里它给了我输出 -

[Chris, Lois, Meg, Meg, Brain, Peter, Stewie]
[Chris, Lois, Meg, Brain, Peter, Stewie]

I am not getting the point, why this is not removing Megbut I have tried with only one Megin that case it is working. And I when I am adding few more Megin last the one Megis not removed from the ArrayList. Why?

我没有明白这一点,为什么这没有删除,MegMeg在这种情况下我只尝试过一个它正在工作。当我Meg最后添加更多时,我Meg没有从ArrayList. 为什么?

采纳答案by tianz

When you remove the first "Meg", the index i=2. Then it's incremented, but since one of the "Meg" is already removed, now name.get(3)is "Brain". So you didn't actually check the second "Meg".

当您删除第一个“Meg”时,索引i=2. 然后它增加了,但是由于“Meg”之一已经被删除,现在name.get(3)是“Brain”。所以你实际上并没有检查第二个“梅格”。

To fix the problem. you can decrement the index when you remove an element:

解决问题。您可以在删除元素时减少索引:

public class ArrayListExp{
    public static void main (String[] args){

        ArrayList<String> name = new ArrayList<String>();

        name.add("Chris");
        name.add("Lois");
        name.add("Meg");
        name.add("Meg");
        name.add("Brain");
        name.add("Peter");
        name.add("Stewie");

        System.out.println(name);

        for ( int i = 0;  i < name.size(); i++){
            String oldName = name.get(i);
            if(oldName.equals("Meg"))
            {
                name.remove(i);
                i--;
            }
        }

        System.out.println(name);
    }
}

回答by Mark Vayngrib

You're removing from the ArrayList while iterating over it from 0 to N, so when you remove the first Meg at index N, the next Meg moves down to index N, then you increment i to N+1. So the 2nd Meg doesn't get removed. Try iterating in the opposite order (N to 0):

您在从 0 到 N 迭代的同时从 ArrayList 中删除,因此当您删除索引 N 处的第一个 Meg 时,下一个 Meg 向下移动到索引 N,然后将 i 增加到 N+1。所以第二个 Meg 不会被移除。尝试以相反的顺序(N 到 0)迭代:

for ( int i = name.size() - 1;  i >= 0; i--) {

回答by Anurag Rana

Its because when i=2 and if condition is true then meg is deleted and all the indices are shifted up. hence the next i will point to Brain, not meg.

这是因为当 i=2 并且条件为真时,则删除 meg 并将所有索引向上移动。因此接下来我将指向 Brain,而不是 meg。

try this. (decrease i by one when if condition holds true)

尝试这个。(如果条件成立,则将 i 减一)

for ( int i = 0;  i < name.size(); i++){
            String oldName = name.get(i);
            if(oldName.equals("Meg"))
            {
                name.remove(i);
                i--;
            }
        }

回答by Kanagaraj M

While removing elements you should not use for loop. It always make problems when implementing some logic. Use reverse for loop for your problem and always try to use for each.

在删除元素时,您不应该使用 for 循环。在实现某些逻辑时,它总是会出现问题。对您的问题使用反向 for 循环,并始终尝试使用 for 每个。

回答by dtgee

You are iterating over the first Meg, and when that Meggets removed, the array values shift over by one.

您正在迭代第一个Meg,当它Meg被删除时,数组值移动一个。

[Chris, Lois, Meg, Meg, Brain, Peter, Stewie]
   0     1     2    3     4      5       6

First Meggets removed, and the loop increments i because it finished executing everything inside the for loop, so iwill now be 3 and the array has been modified:

首先Meg被删除,循环增加 i 因为它完成了 for 循环中的所有内容,所以i现在是 3 并且数组已被修改:

[Chris, Lois, Meg, Brain, Peter, Stewie]
   0     1     2     3      4      5      

Try iterating backwards.

尝试向后迭代。

for ( int i = name.size() - 1;  i >= 0; i--){
    String oldName = name.get(i);
    if(oldName.equals("Meg"))
    {
        name.remove(i);
    }
}

回答by Prabhakaran Ramaswamy

You can use name.removeAll(Arrays.asList("Meg"));to remove all "Meg"

您可以使用name.removeAll(Arrays.asList("Meg"));删除所有"Meg"

Your complete code would be

你的完整代码是

for ( int i = 0;  i < name.size(); i++){
    String oldName = name.get(i);
    if(oldName.equals("Meg"))
    {
       name.removeAll(Arrays.asList("Meg"));
    }
}