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