Summary of methods for iterating through the elements in a list in Java

Source: Internet
Author: User
Tags concurrentmodificationexception

In Java, looping through the list has three ways for loops, enhanced for loops (that is, often called foreach loops), 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 approach is that when you delete an element, the size of the list changes, and your index changes, so you'll miss out on some elements as you traverse. For example, when you delete the 1th element and continue to access the 2nd element according to the index, because the elements behind the deleted relationship move forward one bit, the actual access is the 3rd element. Therefore, this method can be used when deleting a particular element, but not when multiple elements are being recycled.

Because the size of the collection is dynamic, when you delete an element, the sequence number in the element is rearranged, and the second element that should be deleted is now in the position of the first element, the third element is really deleted, and so on, the first, third, and fifth are deleted 、、、、 If you add a statement to the previously deleted code: SYSTEM.OUT.PRINTLN ("the element to be removed:" +list.get (i)), it can be verified.
The result of the output after adding the above statement:
Elements to be removed: a
Elements to be removed: C
Elements to be removed: E
Number of elements remaining: 2
Workaround:
The reason is because you want to delete the element to move forward, and your I save the value is still back, so if I do not go backward, go forward one, you can delete the second position of the element is now ranked in the first position of the element.
The core code after the change:
for (int i=0;i<list.size (); i++) {
SYSTEM.OUT.PRINTLN ("the element to be removed:" +list.get (i));
List.remove (i);
i--;
}
Results:
Elements to be removed: a
Elements to be removed: b
Elements to be removed: C
Elements to be removed: D
Elements to be removed: E
Number of elements remaining: 0

2. Enhanced for Loop

for (String x:list) {    if (x.equals ("del"))        List.remove (x);}

The problem with this approach is that when you delete an element, the loop continues to report the error message concurrentmodificationexception, because the element is being used with concurrent modifications that cause the exception to be thrown. However, when the deletion is complete immediately using break to jump out, it will not trigger an error.

Cause: The Checkforcomodification method throws a Concurrentmodificationexception exception if Modcount is not equal to Expectedmodcount.

Specific reasons and solutions reference: https://www.cnblogs.com/dolphin0520/p/3933551.html#undefined

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 properly cycled and deleted. Note, however, that using the iterator Remove method will also report the Concurrentmodificationexception error mentioned above if you use the Remove method of the list.

Summary of methods for iterating through the elements in a list in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.