简体   繁体   English

如何使用ListIterator编辑列表内容

[英]How To Use ListIterator to Edit a List Content

I'm using a ListIterator to iterate over a list of some object. 我正在使用ListIterator迭代某些对象的列表。 The goal is to edit the contents of the list. 目的是编辑列表的内容。

Here's an example of what I'm doing: 这是我正在做的事的一个例子:

public class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        ArrayList list = new ArrayList<>(Arrays.asList("One", "Two", "Three","Four","Five"));
        ListIterator<String> listIterator = list.listIterator();
        String current ;
        while (listIterator.hasNext()) {
            doSomething(listIterator); 
            current = listIterator.next();
            //here I Want that current has the same value  as it was Before The doSomething Call
            //or in other Word , i want to save the adress of the last visired object In the List before doSomething Call.
    //As a result i can iterate from this point in the List.
            }

        }

    private static ListIterator<String> doSomething(ListIterator<String> listIterator) {
        System.out.println("Dosomething " + listIterator.next()); //
        System.out.println("Dosomething " + listIterator.next()); //
        System.out.println("Dosomething " + listIterator.next()); //
        System.out.println("Dosomething " + listIterator.next()); //
        return listIterator;
    }
}

Could you please give me some insight? 你能给我一些见识吗?

I'm using ListIterator because I want to go forth and back in the list, and for editing purposes. 我之所以使用ListIterator是因为我想在列表中来回移动并进行编辑。

ListIterator keeps track of the current index, so you can save it and rewind after you call doSomething : ListIterator跟踪当前索引,因此您可以保存它并在调用doSomething后倒带:

int pos = listIterator.nextIndex();
doSomething(listIterator);
while (listIterator.nextIndex() > pos) {
    listIterator.previous();
}

This assumes that doSomething only advances the iterator. 假设doSomething仅推进迭代器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM