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
Iterator<string> it = List.iterator (); while (It.hasnext ()) { String x = It.next (); if (X.equals ("del")) { it.remove ();} }
This method can be properly cycled and deleted. Note, however, that using the iterator Remove method will also report the Concurrentmodificationexception error mentioned above if you use the Remove method of the list.
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.
Summary of deleting element methods in List in Java loop