如何引用迭代器中的当前对象

时间:2011-03-02 01:19:28

标签: java iterator

我正在尝试在TreeSet中实现搜索方法。通过使用带有condtional的迭代器,我希望能够遍历集合并打印匹配条件的对象。然而,我现在这样做的方式是打印出后续对象而不是当前对象。 这就是我到目前为止所做的:

public void getDetails() {
        Iterator<Person> it = this.getPersonSet().iterator();
        System.out.println("Enter First Name");
        String first = in.next().toLowerCase();
        System.out.println("Enter Second Name");
        String last = in.next().toLowerCase();

        while (it.hasNext()) {
            if (it.next().getLast().toLowerCase().equals(last)) {
                Person p = it.next();
                System.out.println(p);
            }
        }

    }

任何帮助都会很棒

5 个答案:

答案 0 :(得分:32)

这是你想要做的:

while (it.hasNext()) {
            Person p = it.next();
            if (p.getLast().toLowerCase().equals(last)) {
                System.out.println(p);
            }
        }

答案 1 :(得分:22)

  

如何引用迭代器中的当前对象

对于记录,Iterator API不允许您这样做。没有“当前”对象的概念。 Iterator.next()方法为您提供下一个对象...并继续前进。

ListIterator.previous()ListIterator.next()方法是类似的。请注意,在ListIterator情况下,方法行为是根据表示元素之前/之间/之后的位置的光标记录的在被迭代的序列中。)

解决方案是将调用it.next()的结果分配给临时变量,如接受的答案所述。


我不确定为什么设计师没有在API中包含“当前”对象的概念,但我可以想到几个原因:

  • 它会使典型的迭代器对象更大;即保留当前对象的额外字段。
  • 这意味着要为Iterator类实现更多的方法。
  • 当前对象的概念不适合ListIterator界面中记录的“光标”模型......并且由当前Iterator设计隐含。
  • Iterator有一个小问题“挂在”当前对象上,从而阻止它被GC控制。
  • 绝大多数迭代器用例不需要当前对象。
  • 还有其他方法可以解决这个问题。

听起来很不错......

答案 2 :(得分:3)

如果您需要现有的实施,可以使用Google GuavaApache Commons Collections中的实施 对于你的简单问题,其他答案更容易,但如果你需要传递迭代器并跟踪next()返回的最后一项,这些将有所帮助。

以下是使用带有OP代码的Guava的示例(假设Person确实有String toLowerCase()方法):

import com.google.common.collect.PeekingIterator;
import static com.google.common.collect.Iterators.peekingIterator;

public void getDetails() {
    PeekingIterator<Person> it = peekingIterator(this.getPersonSet().iterator());
    System.out.println("Enter First Name");
    String first = in.next().toLowerCase();
    System.out.println("Enter Second Name");
    String last = in.next().toLowerCase();

    while (it.hasNext()) {
        // note the usage of peek() instead of next()
        if (it.peek().getLast().toLowerCase().equals(last)) {
            Person p = it.next();
            System.out.println(p);
        }
    }

}

答案 3 :(得分:1)

将对象的引用保存在单独的var:

Person current = it.next();
current.methodOne();
current.methodTwo();

当你完成当前值后,重新给它下一个

...
// done? 
current = it.next();

在循环中看起来像:

while( it.hasNext() ) { 
   Person current = it.next();
   current.doA();
   current.doB();
   current.doC();
 }

答案 4 :(得分:0)

next()方法返回当前对象,如下所示:

private class IterSinglyLinked implements SimpleIterator<T> {
    Element curr = head;        // next element to return

    public boolean hasNext() {
        return curr != null;
    }

    public T next() throws Exception {
        if (curr == null) throw new Exception("no more elements");
        T data = curr.data;
        curr = curr.next;
        return data;
    }
}

如果返回的是下一个而不是当前的,则无法到达第一个

相关问题