删除arrayList中的项目:尝试从不存在的索引中删除?

时间:2016-02-29 12:03:41

标签: java arrays for-loop arraylist

我在for-loop内实现逻辑,该逻辑将从狗窝对象中删除状态为“ACCEPTED”的所有狗对象。

请注意,狗窝可以拥有许多狗的列表。

循环:

allDogsInKennel = kennel.getDogsList();
for (int i = 0; i < allDogsInKennel.size(); i++) {
   //delete any dog object with a status of Accepted
   if (allDogsInKennel.get(i).getStatus() == "ACCEPTED") {
     kennel.removeDog(allDogsInKennel.get(i));
   }
}

removeDog方法

 public void removeDog(Dog d) {
        this.dogList.remove(d);
 }

我遇到的问题是列表中的所有6狗应删除,但目前仅删除3

示例:

original size of list = 6 items

Item removed from index 0 = 5 items

Item removed from index 1 = 4 items

item removed from index 2 = 3 items

现在在下一次迭代中,由于index 3条件,循环尝试从i++移除,但数组只会转到index 2,因为它现在只有3索引中的项目:

0, 1, 2

如何更改上面的逻辑以确保从阵列中删除所有项?

1 个答案:

答案 0 :(得分:1)

您可以在从列表中删除对象时添加i--

for (int i = 0; i < allDogsInKennel.size(); i++) {

    //delete any dog object with a status of Accepted
    if (allDogsInKennel.get(i).getStatus().equals("ACCEPTED")) {
        kennel.removeDog(allDogsInKennel.get(i));
        i--   
     }
}

假设你有一个arraylist并且有字符串obj1,obj2,obj3

ArrayList<String> lst = new ArrayList<String>();
lst.add("obj1");
lst.add("obj2");
lst.add("obj3");

for (int i = 0; i < lst.size(); i++) {
     String str = lst.get(i);
     lst.remove(str); //list size decrease, 
     //so when you remove an object with index 0, your new list has obj2(at index 0) and obj3(at index 1) 
     //when i is increased, it will escape obj2, it never check it or access it.
     //i--; //open to give a try
}

for (int i = 0; i < lst.size(); i++) {
    System.out.println(lst.get(i)); //will print obj2
}
  

预计会删除列表中的所有项目,所以我必须添加i--   删除方法后