Method for deleting specific elements in ArrayList loop of Java collection class

In project development, we may often need to dynamically delete some elements in ArrayList.

One wrong way:

The above method will throw the following exception:

Because you delete the element but do not change the subscript of the iteration, you will throw an exception when the iteration reaches the last one.

The above procedure can be improved as follows:

The above code is correct.

Let's introduce another scheme:

The list interface implements the iterator interface internally, providing developers with an iterator () to get an iterator object of the current list object.

The above is also correct, and the second scheme is recommended.

The implementation principles of the two schemes are much worse. The second one is only encapsulated by JDK.

Looking at the source code of ArrayList, you will find that many methods are implemented internally based on the iterator interface, so the second scheme is recommended.

The above is all about the method of deleting specific elements in the ArrayList loop of Java collection class brought by Xiaobian. I hope you can support more programming tips~

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>