我使用ListIterator
迭代某个对象的列表。目标是编辑列表的内容。
以下是我正在做的事情的一个例子:
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;
}
}
你能不能给我一些见解?
我正在使用ListIterator
因为我想要在列表中前后退出并进行编辑。
答案 0 :(得分:0)
ListIterator
会跟踪当前索引,因此您可以在致电doSomething
后保存并快退:
int pos = listIterator.nextIndex();
doSomething(listIterator);
while (listIterator.nextIndex() > pos) {
listIterator.previous();
}
这假设doSomething
只推进迭代器。