开发者

Element goes missing during iteration of Arraylist

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:

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);
            }
        }
    }
}


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 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++));
  }
}


If you take the else out it will give you the desired functionality.

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

    System.out.println(l.get(i));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜