First look at the code below:
Import Java.util.linkedList; Import Java.util.List; Public Class DeleteCollection {Public Static Void Main (String [] ARGS) {list <string> List = NEW Lin Lin kedlist <string> (); list.add ("a" );; ("B"); list.add ("c"); list.add ("d"); list.add ("e"); for (int i = 0; i <list.size (); i ++) {// The element list.remove (i);} System.out.println ("The number of remaining elements:"+list.size ());}}The above code should be right according to the idea, and the result of the output should be 0
Look at the results of the actual output below:
Number of remaining elements: 2
You may ask why? Because the size of the collection is dynamic, when you delete an element, the serial number in the element is re -arranged. The second element that should be deleted is now in the position of the first element, but the real delete is the third third. Push in order, delete the first, third, and fifth ,,,,,, if the statement is added to the original deleted code: System.out.println ("The upcoming deleted element:"+list. get (i)); can be verified.
The result of the output after joining the above statement:
Elements that are about to be deleted: A
Elements that are about to be deleted: C
Elements that are about to be deleted: e
Number of remaining elements: 2
Solution:
The reason is because the elements you want to delete moved forward, and the value of your I store still goes back, so if I let i go back and go forward, you can delete the second one in the second one. The element of the position is now ranked in the first position.
The core code after the change:
for (int i = 0; i <list.size (); i ++) {system.out.println ("" Elements that are about to be deleted: "+list.get (i)); list.remove (i); i-------------------------------------- ;}result:
Elements that are about to be deleted: A
Elements that are about to be deleted: B
Elements that are about to be deleted: C
Elements that are about to be deleted: D
Elements that are about to be deleted: e
Number of remaining elements: 0
The above is all the contents of this article. I hope everyone can like it.