For loop Delete Collection traps

Source: Internet
Author: User

First look at the following code:

import java.util.LinkedList;
import java.util.List;

Public class DeleteCollection {
    
Public static void Main (string[] args) {
list<string> List = new linkedlist<string> ();
List.add ("a");
List.add ("B");
List.add ("C");
List.add ("D");
List.add ("E");
for (int i=0;i<list.size (); i++) {//loops delete elements in the collection
List.remove (i);
        }
System.out.println ("Number of remaining elements:" +list.size ());
    }
}

The code above is supposed to be right, and the output should be 0.

Look at the results of the actual output below:

Number of elements remaining: 2

You might ask why? 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

For loop Delete Collection traps

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.