简体   繁体   English

Java中的迭代器

[英]Iterators in Java

So I have a list of integers for each object of a class.所以我有一个类的每个对象的整数列表。 I am trying to iterate over list of each object, when i encounter a certain condition I move on to the next object and so forth.我试图遍历每个对象的列表,当我遇到某种情况时,我会继续下一个对象,依此类推。

My question here is, when i get back to the pervious object which still has unvisited elements in the list how do I remember the iterator for that particular object.我的问题是,当我回到列表中仍然有未访问元素的上一个对象时,我如何记住该特定对象的迭代器。 Here is the code I have written:这是我写的代码:

void function(Object u, List<Integer> tour, Iterator it) {
Object e;
while (it.hasNext()) {
    e = it.next();
    if (!e.visited) {
        tour.add(e);
        e.visited = true;
        Vertex v = e.otherEnd(e.from);
        v.outgoing++;
        it = v.adj.listIterator(v.outgoing - 1);
        //So instead of re-assigning Iterator it each time is there way //to remember the iterator for each list associated with the object? 
    }
}

Theres three approachs:有以下三种做法:

Use a for on a new iterator (but it will be only for the second level of your graph and repeated code)在新的迭代器上使用 for (但它只会用于图形的第二级和重复代码)

The second one is to change it to recursive.第二种是把它改成递归的。

Or you can do something about having a Stack and be pushing/poping it when necessary.或者你可以做一些关于拥有堆栈的事情,并在必要时推送/弹出它。

Create a map to store the index each iterator has gotten to for an object.创建一个映射来存储每个迭代器为对象获取的索引。 You can update the map when you need to switch to a new object and pull from it whenever you come back to it您可以在需要切换到新对象时更新地图,并在返回时从中拉出

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

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