迭代期间修改和打印ArrayList

我正在尝试同时修改和打印修改后的列表。以下是示例代码:


public class Test {


    static List<Integer> l = new ArrayList<Integer>()

    {{

        add(1);

        add(2);

        add(3);

        add(4);

        add(5);

    }};

    public static void main(String args[])

    {

        performTask();

    }


    private static void performTask()

    {

        int j = 0;

        ListIterator<Integer> iter = l.listIterator();

        while(iter.hasNext())

        {

            if(j == 3)

            {

                iter.add(6);

            }

            System.out.println(l.get(j));

            iter.next();

            ++j;

        }

    }

}

我期待输出,1,2,3,6,4,5但输出是1,2,3,6,4. 另外,如果我想将输出作为1,2,3,4,5,6代码应该如何修改?


慕尼黑5688855
浏览 152回答 2
2回答

慕哥6287543

Iterator在这种情况下,我实际上会放弃。而是尝试这样的代码:List<Integer> list = ...;for (int index = 0; index < list.size(); index++) {&nbsp; &nbsp; final Integer val = list.get(index);&nbsp; &nbsp; // did you want to add something once you reach an index&nbsp; &nbsp; // or was it once you find a particular value?&nbsp;&nbsp;&nbsp; &nbsp; if (index == 3) {&nbsp; &nbsp; &nbsp; &nbsp; // to insert after the current index&nbsp; &nbsp; &nbsp; &nbsp; list.add(index + 1, 6);&nbsp; &nbsp; &nbsp; &nbsp; // to insert at the end of the list&nbsp; &nbsp; &nbsp; &nbsp; // list.add(6);&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(val);}由于 for 循环i与size()每次迭代进行比较,并且size()在将元素添加到列表时进行更新,因此这会正确打印添加到列表中的新内容(只要它们添加在当前索引之后)。

慕少森

xtratic 的答案的主题在展示满足 OP 的要求需要做什么方面非常出色(竖起大拇指),但代码不能很好地完成工作,因此发布此代码正是 OP 想要的,List<Integer> list = new ArrayList<>();list.add(1);list.add(2);list.add(3);list.add(4);list.add(5);for (int index = 0; index < list.size(); index++) {&nbsp; &nbsp; final Integer val = list.get(index);&nbsp; &nbsp; if (index == 3) { // index doesn't have to be compared with 3 and instead it can be compared with 0, 1 or 2 or 4&nbsp; &nbsp; &nbsp; &nbsp; list.add(5, 6); // we need to hardcodingly add 6 at 5th index in list else it will get added after 4 and will not be in sequence&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(val);}这输出以下序列,123456在 for 循环中,如果我们这样做,list.add(index+1, 6);然后它会产生错误的序列,因为在第 4 个索引处添加了 6。123465
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java