The for loop in Java removes the collection trap

  • 2020-04-01 03:51:13
  • OfStack

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++){ //The loop deletes elements from the collection
      list.remove(i);
    }
    System.out.println(" The number of remaining elements: "+list.size());
  }
}

The above code should be correct, and the output should be 0

Look at the actual output below:

The number of elements left: 2

Why, you might ask? Because of the size of the collection is a dynamic change, when you delete an element, the element of the serial number and rearrange, originally should remove the second element is now in the position of the first element, really delete is the third element, so on, remove the is the first, third, fifth,,,,, if in the original delete code to join statement: System. Out. The println (" is going to delete elements: "+ list. Get (I)); You can verify.

Output results after adding the above statement:

The element to be deleted: a
The element to be deleted: c
The element to be deleted: e
The number of elements left: 2

Solutions:

The reason is that the element you want to delete has moved forward, while the value of your "I" is still moving forward. Therefore, if you let "I" go forward instead of backward, you can delete the element that was in the second position and now is in the first position.

Core code after the change:


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

Results:

The element to be deleted: a
The element to be deleted: b
The element to be deleted: c
The element to be deleted: d
The element to be deleted: e
The number of elements left: 0

The above is all the content of this article, I hope you can enjoy it.


Related articles: