The idea of looping through the list of elements using a for loop is problematic, but you can use the enhanced for loop, and then find an error today when using it, then go to science a bit, and then find that this is a misunderstanding. Here's a talk. The party can jump directly to the end of the text. See Summary:
In Java, looping through the list has three ways for loops, enhanced for loops (that is, often called foreach loops), and iterator traversal.
1. For loop traversal list
for (int i=0;i<list.size (); i++) {
if (List.get (i). Equals ("Del"))
List.remove (i);
}
The problem with this approach is that when you delete an element, the size of the list changes, and your index changes, so you'll miss out on some elements as you traverse. For example, when you delete the 1th element and continue to access the 2nd element according to the index, because the elements behind the deleted relationship move forward one bit, the actual access is the 3rd element. Therefore, this method can be used when deleting a particular element, but not when multiple elements are being recycled.
2. Enhanced for Loop
for (String x:list) {
if (X.equals ("Del"))
List.remove (x);
}
The problem with this approach is that when you delete an element, the loop continues to report the error message concurrentmodificationexception, because the element is being used with concurrent modifications that cause the exception to be thrown. However, when the deletion is complete immediately using break to jump out, it will not trigger an error.
3. Iterator traversal
Copy Code
Iterator
Summarize:
(1) to cycle through the list of specific elements, you can use any of the three ways, but in use should pay attention to the above analysis of the various issues.
(2) to iterate over multiple elements in a list, you should use the iterator iterator method.
Original link: https://www.cnblogs.com/pcheng/p/5336903.html
Summary of methods for iterating through the elements in a list in Java