Preface
The reason for introducing enhanced for loops: In previous versions of JDK5, it is more troublesome to traverse elements in an array or collection and iterator of the array length or collection.
A new syntax is defined in JDK5 - enhanced for loops to simplify such operations. Enhanced for loops can only be used on arrays or collections that implement Iterable interfaces.
Syntax format:
for(variable type variable: array or collection that needs to be iterated) {
}
In JAVA, traversing collections and arrays generally have the following 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 + ",");} The first is ordinary for loop traversal, the second is to use iterators for traversal, and the third is generally called enhanced for loop (for each).
Implementation principle
It can be seen that the third form is syntactic sugar provided by JAVA. Here we analyze how this enhanced for loop is implemented in the underlying layer.
We decompile the following code:
for (Integer i : list) { System.out.println(i);}After decompilation:
Integer i;for(Iterator iterator = list.iterator(); iterator.hasNext(); System.out.println(i)){ i = (Integer)iterator.next(); } The decompiled code is actually quite complicated, so let's break it down in the order of execution:
Integer i; defines a temporary variable i
Iterator iterator = list.iterator(); Get the iterator of List
iterator.hasNext(); determines whether there are untraversed elements in the iterator
i = (Integer)iterator.next(); Get the first untraversed element and assign it to the temporary variable i
System.out.println(i) outputs the value of the temporary variable i
This cycles until all elements in the List are traversed.
Through decompilation, we see that the underlying layer of enhanced for loops in JAVA is actually implemented through the iterator pattern.
The pit of enhancing the for loop
This is said to be a pit in the enhancement for loop, but it is actually mainly because some people may step into the pit in the implementation principle of the enhancement for loop.
Since the enhancement for loop is implemented through an iterator, it must have the characteristics of an iterator.
There is a fail-fast mechanism in Java. When using an iterator to traverse elements, you must be careful when deleting the collection. If you use it improperly, ConcurrentModificationException may occur. This is a runtime exception and will not occur during the compilation period. It will only explode when the program is actually running.
As in the following code:
for (Student stu : students) { if (stu.getId() == 2) students.remove(stu); }A ConcurrentModificationException exception will be thrown.
Iterator works in a separate thread and has a mutex lock. After the Iterator is created, a single-link index table pointing to the original object. When the number of original objects changes, the content of this index table will not change synchronously, so when the index pointer moves backward, the object to iterate cannot be found, so according to the fail-fast principle, Iterator will be thrown immediately.
java.util.ConcurrentModificationException exception.
Therefore, iterator does not allow iterated objects to be changed when it works.
But you can use the Iterator's own method remove() to delete the object. Iterator.remove() method will maintain the consistency of the index while deleting the current iterated object.
Correctly delete elements while traversing:
Iterator<Student> stuIter = students.iterator(); while (stuIter.hasNext()) { Student student = stuIter.next(); if (student.getId() == 2) stuIter.remove();// Here you need to use the remove method of Iterator to remove the current object. If you use the remove method of List, ConcurrentModificationException will also appear } OK, here I will introduce you to the implementation principle of enhancing the for loop and the pitfalls you may fall into if you use it improperly. Therefore, although it is a simple for-each syntax, you must also understand its principles, otherwise it may lead to some inexplicable problems.
Summarize
The above is the entire content of this article. I hope that the content of this article has certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support to Wulin.com.