ArrayList uses the remove method to remove elements in the for loop

Sometimes we need to dynamically delete the requirements of elements in an ArrayList for loop. Let's not talk about the nonsense and look at the code

Execute the code and the result is as follows:

It can be seen that before deletion, the number corresponding to the item and cycle of our list are correct, but after deleting the fourth element in the following cycle, the number corresponding to Item 4, 5 and 6 should have been 4,6, but here it has become 5,7

The reason is that after we delete item 4, the length of the list becomes 7, and the list will move the value after item 4 forward one bit, that is, when I = 3, the list When get (I) = 4, I = 4, list When get (I) = 5, I = 5, list When get (I) = 6, I = 6, list get(i)=7.. The image we want to talk about is that there are 8 layers of pastries, 0-7 in turn, standing up, the big one is on the top and the small one is on the bottom. When we count from bottom to top to the fifth, we eat this layer of pastries. At this time, the upper three layers move down one layer respectively. Therefore, we don't cycle the items with a value of 4 at all

What is the way to remove? A stupid way is to create a new templist, add all the items to be deleted, and finally use list RemoveAll (templist) implementation But here we have a better method, which is to delete in reverse order

Let's look at the code from the above example:

Execute the code and the result is as follows:

We can see that changing the cycle and deleting does not affect the following elements, and the list after removing is the same as the first result This is because we delete the list element. The length of the list will become smaller, but only the items larger than the items of the currently deleted element will change. We use the reverse order loop here. We have executed the large items, so it will not affect Then use the above metaphor to illustrate that this time we count from top to bottom. When we count to the fourth, the upper three layers move down one layer respectively, but this does not affect the cakes we have counted before, nor does it affect the cakes below. This is the principle

summary

The above is all about how ArrayList uses the remove method to remove elements in the for loop. I hope it will be helpful to you. Interested friends can refer to: simple example of Java implementation skip list, detailed explanation of Java multithreaded forkjoinpool instance, etc. Thank you for your support for the programming tips website. If you have any questions or want to know, you can leave us a message at any time. Xiaobian will reply to you in time.

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
分享
二维码
< <上一篇
下一篇>>