Iterable implementation with 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. (He claims that he cannot find the type "Entry" in the definition of the ItemList class).

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

My question is: why is this not compiling? And what is the best way to solve this problem?

+4
source share
2 answers

The problem is defining the area. Since Entry is an inner class, it must have a prefix of the name "parent". Try the following:

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

An entry is a private class, so other classes will not be able to see it. you can make it public, but still keep it nested.

It must also be static, because it does not depend on any state of the outer class.

+1
source

All Articles