Can somebody explain to me whats wrong with the below piece of code ?
public static void main(String[] args) {
List<String> l = new ArrayList<String>();
l.add("1");
l.add("2");
l.add("3");
l.add("4");
for (int i = 0; i < l.size(); i++) {
if(l.get(i).equals("1"))
l.remove(l.get(i));
else
System.out.println(l.get(i));
}
}
gives me an output of [3.4] instead of [2,3,4] .. Wheres my [2] ? I am a lil confused with this behavior of the List.. Great if somebody could explain..
Thanks in advance 🙂
The reason is:
When i = 0 you remove the first element and i becomes 1
When i = 1 you are now at the third element, because you have shifted everything down by 1 so you write “3”
When i = 2 you write the third element which is “4”
Giving you an output of “3”,”4″
An alternate implementation might be: