Summarize:
1, the disadvantage of For-each cycle: lost the index information.
When traversing a collection or array, if you need to access the index of a collection or array, it is best to use the old-fashioned way to loop or traverse, rather than using an enhanced for loop, because it loses subscript information.
Enhanced for loop usage
1. The effect of first enhancing for loop and iterator traversal is the same, it is said that the internal of the enhanced for loop is called Iteratoer implementation,
However, there are some drawbacks to enhancing the For loop, such as not being able to dynamically delete collection contents in an enhanced loop. Cannot get subscript and so on.
2.ArrayList because of the use of arrays implementation, so the subscript is clear, it is best to use the normal loop.
3. For LinkedList because it takes an element to get back from the beginning, it is recommended to use an enhanced for loop, which is iterator.
The following example can prove
Press CTRL + C to copy code press CTRL + C to copy code
Use ArrayList to run the results as follows
Change the ArrayList to LinkedList, I have a memory overflow here, the result is as follows
So the list is changed to 50000 and the results are as follows
So when you use it, it's good to choose.
Enhanced for loop usage ___arraylist array implementation use subscript best, LinkedList use Enhanced (reprint)