I remember that there is a problem with using the for loop to delete elements in the list, but you can use the enhanced for loop. Then today I found that an error was reported when using it, and then went to popularize the science, and then found that this was a misunderstanding. Let’s talk about it below. . Reach out and jump directly to the end of the article. Look at the summary. .
There are three ways to loop traverse lists in JAVA, enhance for loop (that is, the commonly known as foreach loop), 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 method is that after deleting an element, the size of the list changes, and your index changes, which will cause you to miss certain elements during traversal. For example, when you delete the first element and continue to access the second element according to the index, because the elements after the deleted relationship are moved one by one, the actual access to the third element. Therefore, this method can be used when deleting a specific element, but is not suitable when deleting multiple elements in a loop.
2. Enhance the for loop
for(String x:list){ if(x.equals("del")) list.remove(x);}The problem with this method is that after deleting the element, the error message will be reported by continuing to loop, because concurrent modification occurs when the element is used, resulting in exception thrown. However, if you use break to jump out immediately after deletion, an error will not be triggered.
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 looped and deleted normally. But it should be noted that if you use the remove method of iterator, if you use the remove method of the list, you will also report the ConcurrentModificationException error mentioned above.
Summarize:
(1) If you loop to delete a specific element in the list, you can use any of the three methods, but you should pay attention to the various issues analyzed above when using it.
(2) If you loop to delete multiple elements in the list, you should use the iterator method.
The above summary of the above method of deleting elements in lists in java is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.