Java code farm must master the correct way to delete List elements in a circular way!

Let's first look at the following examples of deleting list elements

public static void main(String\[\] args) {

    List<String> list = new ArrayList<>(Arrays.asList("a1", "ab2", "a3", "ab4", "a5", "ab6", "a7", "ab8", "a9"));

    /**

     * Report errors

     * java.util.ConcurrentModificationException

     */

    for (String str : list) {

        if (str.contains("b")) {

            list.remove(str);

        }

    }

    /**

     * Error reporting: subscript out of range

     * java.lang.IndexOutOfBoundsException

     */

    int size = list.size();

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

        String str = list.get(i);

        if (str.contains("b")) {

            list.remove(i);

        }

    }

    /**

     * Normal deletion, size method is called every time, performance is lost, not recommended

     */

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

        String str = list.get(i);

        if (str.contains("b")) {

            list.remove(i);

        }

    }

    /**

     * **Normal deletion, recommended**

     */

    for (Iterator<String> ite = list.iterator(); ite.hasNext();) {

        String str = ite.next();

        if (str.contains("b")) {

            ite.remove();

        }

    }

    /**

     * Report errors

     * java.util.ConcurrentModificationException

     */

    for (Iterator<String> ite = list.iterator(); ite.hasNext();) {

        String str = ite.next();

        if (str.contains("b")) {

            list.remove(str);

        }

    }

}

We understand that the dynamic deletion of elements causes the array subscript to be out of bounds.

What about ConcurrentModificationException?

Among them, for(xx in xx) is an enhanced for loop, i.e. the enhanced implementation of Iterator. The internal part is the method of Iterator called. Why do we report the ConcurrentModificationException error? Let's look at the source code

When you take down an element, you will judge whether the quantity to be modified is consistent with the quantity expected to be modified. If it is inconsistent, an error will be reported. If you call the remove method through the iterator itself, you will not have this problem, because the two quantities will be synchronized when it is deleted. It's easy to understand why it's an added for loop.

Recommend to my blog to read more:

1.Java JVM, collection, multithreading, new features series

2.Spring MVC, Spring Boot, Spring Cloud series tutorials

3.Maven, Git, Eclipse, Intellij IDEA series tools tutorial

4.Latest interview questions of Java, backend, architecture, Alibaba and other large factories

Feel good, don't forget to like + forward!

Tags: Programming Java Spring jvm Maven

Posted on Wed, 29 Apr 2020 08:02:44 -0700 by nodehopper