0

I am trying to iterate through an ArrayList and remove the actual object (index s) under certain conditions (x == 0). It always gives an error at the line where the object should be removed, if executed. Without the remove() it runs perfectly fine.

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");
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
user11740260
  • 143
  • 1
  • 7

3 Answers3

1

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>)). In fact, Iterator#remove exists pretty much exactly for this reason:

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:

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
Rogue
  • 11,105
  • 5
  • 45
  • 71
0

Each time you remove an element from a List using an index, the List shrinks because the succeeding elements shift one place left/down. 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<YourType> itr = objectList.iterator();
while (itr.hasNext()) {
    YourType obj = itr.next();
    if (some condition) {
        itr.remove();
    }
    // ...
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
0

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);
PrasadU
  • 2,154
  • 1
  • 9
  • 10