Implementing Iterable with a nested class in Java

generics, iterator, java

Solution

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();
    }
}

Problem

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?

Original source