问题描述
我有以下代码-
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]
我没明白为什么这不删除 Meg
但我只尝试了一个 Meg
在这种情况下它可以工作.当我在最后添加更多 Meg
时,一个 Meg
不会从 ArrayList
中删除.为什么?
I am not getting the point, why this is not removing Meg
but I have tried with only one Meg
in that case it is working. And I when I am adding few more Meg
in last the one Meg
is not removed from the ArrayList
. Why?
推荐答案
当您删除第一个Meg"时,索引 i=2
.然后它增加,但由于Meg"之一已经被删除,现在 name.get(3)
是Brain".所以你实际上没有检查第二个梅格".
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".
解决问题.您可以在删除元素时减少索引:
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);
}
}
这篇关于ArrayList.remove 不在循环中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!