The impression in the loop delete the elements in the list there is a problem with the For loop, but you can use the enhanced for loop, and then today in use to find the error, and then go to the science, and then found that this is a misunderstanding. Here's a talk. Reach the party can jump directly to the end of the article. Look at the summary.
There are three ways to iterate through the list in Java, for loops, enhanced for loops (that is, commonly called foreach loops), 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, which can cause you to omit some elements while traversing. For example, when you delete the 1th element and continue to access the 2nd element based on the index, because the elements behind the deleted relationship move one bit forward, the actual access is the 3rd element. Therefore, this approach can be used when deleting a particular element, but is not appropriate for iterating over multiple elements.
2. Enhance for loop
for (String x:list) {
if (x.equals ("del"))
List.remove (x);
}
The problem with this approach is that the continuation of the loop after deleting the element will report the error message concurrentmodificationexception because the element was used with concurrent modifications, causing the exception to be thrown. But the deletion completes immediately uses the break to jump out, does not trigger the error.
3, iterator traversal
Iterator<string> it = List.iterator ();
while (It.hasnext ()) {
String x = It.next ();
if (X.equals ("del")) {
it.remove ();
}
}
This way can be normal loop and delete. Note, however, that using the iterator Remove method will also report the Concurrentmodificationexception error mentioned above if the Remove method of the list is used.
Summarize:
(1) To delete a particular element in a list, you can use any of the three methods, but in use you should pay attention to the problems analyzed above.
(2) To remove multiple elements in a list, you should use the iterator iterator method.
The above in the Java loop Delete list elements of the method summary is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.