简体   繁体   English

迭代器实现导致无限循环

[英]Iterator implementation causing infinite loop

I am trying to do a foreach loop as followed for a linkedlist-esque class I built: 我正在尝试为我构建的链表式类进行如下的foreach循环:

boolean contains = false;
for(Thing t : front) {
    if(t.equals(something)) {
        t.doSomething();
        contains = true;
        break;
    } 
}

This are the iterator methods I've implemented: 这是我实现的迭代器方法:

@Override
public Iterator<Thing> iterator() {
    Thing current = this;
    return new Iterator<Thing>() {
        public boolean hasNext() {
            return current.hasNext();
        }

        public Thing next() {
            return current.next;
        }
    };
}

I've tried debugging this and it seems it isn't returning the next element in the linkedlist, thus causing an infinite loop when I run it and try and do a foreach loop. 我已经尝试调试此方法,似乎它没有返回链表中的下一个元素,因此在运行它并尝试执行foreach循环时会导致无限循环。

Sorry if this question has been answered or there's a really stupid mistake, I searched for a while and couldn't find an answer. 很抱歉,如果这个问题已经回答,或者确实有一个愚蠢的错误,我搜索了一段时间却找不到答案。 This is my first time writing an iterator so please be gentle. 这是我第一次编写迭代器,请保持谨慎。 :) :)

You have to advance the Iterator 's state in next() : 您必须在next()推进Iterator的状态:

    public Thing next() {
        current = current.next;
        return current;
    }

Otherwise, all calls to next() would return the same element. 否则,所有对next()调用都将返回相同的元素。

EDIT : 编辑:

You should move your local variable declaration Thing current = this; 您应该移动局部变量声明Thing current = this; inside your anonymous class instance (ie turn it into an instance variable). 在您的匿名类实例中(即将其转换为实例变量)。

@Override
public Iterator<Thing> iterator() {
    return new Iterator<Thing>() {

        private Thing current = Thing.this;

        public boolean hasNext() {
            return current.hasNext();
        }

        public Thing next() {
            current = current.next;
            return current;
        }

    };
}

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

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