Win a copy of The Business Blockchain this week in the Cloud forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem While Removing Element From List

 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

output is-> 1 3
i am not able to understand why 1 and 3 is not removed from List.
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 697
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Gautam Malik
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try out this:

////////////////////////////////////////////////////////////////////////////
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
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
dennis du
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should use iterator to remove them.

Iterator iterator=list.iterator();
while(iterator.hasNext()){
iterator.remove();
}


So you can scan and remove all of them. It is more reasonable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic