Method summary of circular deletion of elements in list in Java
In my impression, there is a problem with the way to use the for loop to delete the elements in the list, but you can use the enhanced for loop. Today, when you use it, you find that there is an error. Then you go to popularize science, and then you find that this is a misunderstanding. Let's talk about it.. Reach out and jump directly to the end of the text. Look at the summary..
In Java, there are three ways to loop through the list: for loop, enhanced for loop (that is, foreach loop) and iterator.
1. For loop traversal list
The problem with this method is that after deleting an element, the size of the list changes and your index changes, so you will miss some 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 behind the deleted relationship move forward by one bit, you actually access the third element. Therefore, this method can be used when deleting a specific element, but it is not suitable for circular deletion of multiple elements.
2. Enhanced for loop
The problem with this method is that the error message concurrentmodificationexception will be reported if the loop continues after deleting the element, because the element is modified concurrently during use, resulting in an exception being thrown. However, if you use break to jump out immediately after deletion, an error message will not be triggered.
3. Iterator traversal
This method can cycle and delete normally. However, it should be noted that if the remove method of iterator is used, the concurrenctmodificationexception error mentioned above will also be reported if the remove method of list is used.
Summary:
(1) For circular deletion of a specific element in the list, you can use any of the three methods, but you should pay attention to the problems analyzed above.
(2) Iterator iterator should be used to delete multiple elements in the list.
The above summary of the method of circular deletion of elements in the list in Java is all the content shared by Xiaobian. I hope it can give you a reference and support more programming tips.