output is-> 1 3 i am not able to understand why 1 and 3 is not removed from List.
wise owen
Ranch Hand
Joined: Feb 02, 2006
Posts: 2023
posted
0
Because i add 1 in each loop. 1) i=0, remove "0"; The "1" element move to index 0 and l.size()=3 2) i=1, remove "2"; The "3" element move to index 1 and l.size()=2 3) i=2, exit loop because the condition of "i<l.size();" [ August 04, 2006: Message edited by: wise owen ]
Paul Michael
Ranch Hand
Joined: Jul 02, 2001
Posts: 697
posted
0
wise is correct. try to remove the elements from the list backwards. using highest indeces first. that way, it won't mess up your for loop.
//////////////////////////////////////////////////////////////////////////// import java.util.*; class test { public static void main(String args[]){ List<String> l=new ArrayList<String>(); l.add("0"); l.add("1"); l.add("2"); l.add("3"); int size = l.size(); for(int i=0; i < size ; i++){ System.out.println("Removing "+l.get(0)); l.remove(0); System.out.println("Size is now: "+l.size()); } for(int i=0;i<l.size();i++){ System.out.println(l.get(i)); } } } //////////////////////////////////////////////////////////////////////////
Yatendra Varshney
Greenhorn
Joined: Jan 30, 2006
Posts: 5
posted
0
Hi,
See, your code is running in follwoing manner: 1. Go to first for loop: size of list is 4 and value of i =0. 2. First Attampt: In for loop i < l.size() means 0<4, condition is true go to inside loop and remove "0" from the list and "1" moved to 0th location of the list, now value of list is 3 and i is 1. Second Attampt: Again go to inside loop and remove "2" because "2" on the 1st position, and then "3" moved to 1th location and then i is 2 and size of list is 2 then condition is false.
So you can scan and remove all of them. It is more reasonable.
-------------------------------<br />OCP 9i <br />SCJP/SCJD/SCWCD(92%)/SCDJWS<br />XML(IBM Test 141)<br />Who is the next?SCBCD<br />SCBCD/CCNA/CCNP/PMP<br />not sure
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.