Stepping on the pit record--list.remove() method trap

One, first talk about the correct way

1. Let the index be adjusted synchronously

        for (int i = 0; i < list.size(); i++) {
            Apple apple = list.get(i);
            if(apple.getWeight()==23){
                list.remove(i--);
            }
        }

2. Traverse the List in reverse order to delete elements

        for (int i = list.size() - 1; i >= 0; i--) {
            Apple apple = list.get(i);
            if (apple.getWeight() == 23) {
                list.remove(i);
            }
        }

3. The Iterator.remove() method will delete the current iteration object while retaining the index of the original element. This method is recommended.

        Iterator<Apple> iterator = list.iterator();
        while (iterator.hasNext()) {
            Apple apple = iterator.next();
            if (apple.getWeight() == 23) {
                iterator.remove();
            }
        }

Second, the wrong way to delete

1. Positive order traversal

        for (int i = 0; i < list.size(); i++) {
            Apple apple = list.get(i);
            if(apple.getWeight()==23){
                list.remove(i);
            }
        }

2. Iteratively traverse, use the list.remove(i) method to delete elements, and throw an exception: java.util.ConcurrentModificationException

        Iterator<Apple> iterator = list.iterator();
        while (iterator.hasNext()) {
            Apple apple = iterator.next();
            if (apple.getWeight() == 23) {
                list.remove(apple);
            }
        }

3. Forech is deleted, and an exception is thrown: java.util.ConcurrentModificationException

        for (Apple apple : list) {
            if (apple.getWeight() == 23) {
                list.remove(apple);
            }
        }

 

Guess you like

Origin blog.csdn.net/qq_36336332/article/details/107191910