假设我们有一个猫的ArrayList。
这是我们的猫:
public class Cat{
String color;
int age;
public Cat(String color, int age){
this.color = color;
this.age = age;
}
}我们有一只猫,每只猫都有一种颜色。在代码中的其他地方,我们有以下内容:
ArrayList<Cat>cats = new ArrayList<Cat>();
cats.add(new Cat("white",5);
cats.add(new Cat("black",6);
cats.add(new Cat("orange",10);
cats.add(new Cat("gray",3);
System.out.println(cats.size()); prints out 4现在是猫,ArrayList有4只猫在里面。如果我想移除所有5岁以上的猫,难道我不应该这样做吗?
for(int index = 0; index<cats.size(); index++){
if(cats.get(index).age > 5){
cats.remove(index);
}
}现在运行之后,我打印出猫的大小ArrayList和它说3,即使它应该删除3猫,留下一个。
,所以,这不应该起作用吗?我不明白为什么不会。还有什么其他方法可以从列表/数组中删除具有特定值的对象呢?
发布于 2016-11-30 00:56:18
您的示例的问题是,您正在从cat数组中删除一个项,但没有考虑到新的大小。正在发生的事情是:
如果确定要使用for循环,最简单的解决方案是每次删除元素时将索引减少一个,如下所示:
for(int index = 0; index<cats.size(); index++){
if(cats.get(index).age > 5){
cats.remove(index);
index = index - 1; // Accounting for index of elements ahead changing by one
}
}https://stackoverflow.com/questions/40878430
复制相似问题