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.