views:

60

answers:

3

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 :)

+2  A: 

After you call l.remove, the current element (l.get(i)) ends up being the next element ("2").
However, after calling remove, you continue the loop and end up skipping the element.

To fix this, you can add i-- inside the if so that the new current element gets processed by the next iteration (after i++)

SLaks
+1  A: 

SLaks is correct as to what the problem is might i suggest syntax more like this.

int i=0;
while(i < l.size())
{
  if(l.get(i).equals("1"))
    l.remove(l.get(i));
  else
  {
    System.out.println(l.get(i++));
  }
}
davydotcom
ok.. An iterator did the job for me.. But ya. crappy mistake.. Thanks again guys :)
paypalcomp
+5  A: 

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:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Item {
    public static void main(String[] args) {
        List<String> l = new ArrayList<String>();
        l.add("1");
        l.add("2");
        l.add("3");
        l.add("4");

        Iterator<String> iter = l.iterator();
        while(iter.hasNext())
        {
            String value = iter.next();
            if("1".equals(value))
            {
                iter.remove();
            }
            else
            {
                System.out.println(value);
            }
        }
    }
}
Romain Hippeau
You should definitely use Iterator to remove elements whenever possible, to avoid having to manually decrement the index variable. It's a lot safer this way. Of course you can't always use it, but if you can, please do.
Andrei Fierbinteanu