In JAVA, iterating over collections and arrays generally takes one of three forms:

for (int i = 0; i < list.size(); i++) {
    System.out.print(list.get(i) + ",");
}

Iterator iterator = list.iterator();
while (iterator.hasNext()) {
    System.out.print(iterator.next() + ",");
}

for (Integer i : list) {
    System.out.print(i + ",");
}
Copy the code

The first is plain for loop traversal, the second is traversal using iterators, and the third is commonly called enhanced for loop (for each).

Realize the principle of

As you can see, the third form is the syntactic sugar provided by JAVA, and here we take a look at how this enhanced for loop is implemented at the bottom.

We decompiled the following code:

    for (Integer i : list) {
       System.out.println(i);
   }
Copy the code

After decompiling:

    Integer i;
    for(Iterator iterator = list.iterator(); iterator.hasNext(); System.out.println(i)){
        i = (Integer)iterator.next();        
    }
Copy the code

The decomcompiled code is actually quite complex, so let’s disassemble it in order of execution:

Integer i; Define a temporary variable I

Iterator iterator = list.iterator(); Gets the iterator for the List

iterator.hasNext(); Determines if there are any untraversed elements in the iterator

i = (Integer)iterator.next(); Gets the first untraversed element and assigns it to the temporary variable I

System.out.println(I) prints the value of the temporary variable I

Repeat until all the elements in the List are iterated.

Through decompilation, we can see that enhanced for loops in JAVA are implemented at the bottom through the iterator pattern.

pit

Since enhanced for loops are implemented through iterators, they must have iterator properties. This is described in the Fail-fast mechanism in Java. When using iterators iterate through elements, at the time of the collection to delete it is important to note that the possible ConcurrentModificationException improper use, such as the following:

for (Student stu : students) {    
    if (stu.getId() == 2)     
        students.remove(stu);    
}
Copy the code

Will throw ConcurrentModificationException.

Iterator works on a separate thread and has a mutex lock. After the Iterator is created, it creates a single indexed table that points to the original object. When the number of original objects changes, the contents of the index table do not change synchronously. Therefore, when the index pointer moves backwards, the object to be iterated cannot be found. So the Iterator thrown immediately in accordance with the principle of fail – fast Java. Util. ConcurrentModificationException anomalies.

So the Iterator does not allow the iterated object to be changed while working. But you can remove objects using Iterator’s own method, remove(),Iterator.remove()Method maintains index consistency while deleting the current iteration object.

Correct position to delete elements while traversing:

Iterator<Student> stuIter = students.iterator(); while (stuIter.hasNext()) { Student student = stuIter.next(); if (student.getId() == 2) stuIter.remove(); / / here to use Iterator remove method to remove the current object, if use the remove method, also can appear ConcurrentModificationException}Copy the code