那张元素ArrayList的迭代过程中失踪 [英] Element goes missing during iteration of Arraylist

查看:99
本文介绍了那张元素ArrayList的迭代过程中失踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我解释一下什么是错的下篇code的?

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

给我,而不是[3.4]的输出[2,3,4] ..我哪来[2]?我对名单的这种行为感到困惑律..伟大的,如果有人能解释..

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..

在此先感谢:)

推荐答案

的原因是:结果
当i = 0删除第一个元素,我变成1结果
当i = 1,你现在是在第三个元素,因为你已经被转移1的一切,所以你写的3的结果
i = 2时你写的第三个元素是4

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"

给你的3的输出,4

另一种实现可能是:

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

这篇关于那张元素ArrayList的迭代过程中失踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆