2

I am trying to do a foreach loop as followed for a linkedlist-esque class I built:

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.

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. :)

1 Answer 1

6

You have to advance the Iterator's state in next() :

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

Otherwise, all calls to next() would return the same element.

EDIT :

You should move your local variable declaration Thing current = this; inside your anonymous class instance (i.e. 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;
        }

    };
}
Sign up to request clarification or add additional context in comments.

4 Comments

When I do this, I get an error in Eclipse: "Local variable current defined in an enclosing scope must be final or effectively final". I tried changing the next method to the following: public Thing next() { Thing tmp = current; tmp = current.next; return tmp; } But it is still not advancing to the next element in the list.
@Tbs95 An anonymous class in a method does not have alteration rights on variables inside the enclosing method. You need to make the current variable an instance variable of the Iterator, because it is part of the iterator's state.
Thank you @Eran, but now that I have changed the variable declaration location, I am getting a Type Mismatch error converting new Iterator<Thing>(){} to Thing.
Gosh, I swear I already tried that and it gave me a different error... Worked flawlessly though, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.