Java for-loop Delete collection traps _java

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& Lt 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 elements remaining:" +list.size ());
  }


The code 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 set is dynamically changing, when you delete an element, the sequence number in the element is rearranged, the second element that should be deleted is now in the position of the first element, but the third element is actually deleted, and so on, the first, third, fifth 、、、、 If you add a statement to the previously deleted code: SYSTEM.OUT.PRINTLN ("the element to be deleted:" +list.get (i));

The result of the output after adding the above statement:

Elements about to be deleted: a
Elements to be deleted: C
Elements about to be deleted: E
Number of elements remaining: 2

Solution:

The reason is because you want to delete the elements moved forward, and your I save the value is still back, so if I do not go back, go forward one, you can delete the elements in the second position is now ranked in the first position of the elements.

Changed core code:

  for (int i=0;i<list.size (); i++) {
      System.out.println ("element to be deleted:" +list.get (i));
      List.remove (i);
      i--;
    }

Results:

Elements about to be deleted: a
Elements about to be deleted: b
Elements to be deleted: C
Elements about to be deleted: D
Elements about to be deleted: E
Number of elements remaining: 0

The above mentioned is the entire content of this article, I hope you can enjoy.

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.