Reputation: 43
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
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
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