jareds
jareds

Reputation: 43

Implementing Iterable with a nested class in Java

Here is my code:

import java.util.List;

public class ItemList implements Iterable<Entry> {
    private List<Entry> entries;

    public static class Entry {
        private final String id;
        private int quantity;
    }

    @Overide public Iterator<Entry> iterator() {
        return entries.iterator();
    }
}

This code will not compile. (It claims it cannot find the "Entry" type in the ItemList class definition).

I want other classes to be able to iterate over the internal entries of this List. I would rather not move the Entry class to a separate file, as that would require exposing many of the inner workings of that class to all of the other classes in the package.

My question is then: Why won't this compile? And, what is the best way around this problem?

Upvotes: 4

Views: 1138

Answers (2)

Tudor
Tudor

Reputation: 62439

The problem is scoping. Since Entry is an inner class it needs to be prefixed by the name of the "parent". Try this:

class ItemList implements Iterable<ItemList.Entry> {

    private List<Entry> entries;

    public static class Entry {
        private final String id = null;
        private int quantity;     
    }

    @Override public Iterator<Entry> iterator() {
        return entries.iterator();
    }
}

Upvotes: 9

Jeff Storey
Jeff Storey

Reputation: 57192

Entry is a private class so other classes won't be able to see it. you can make it public but still keep it nested.

It should also be static since it doesn't depend on any state of the outer class.

Upvotes: 1

Related Questions