Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
jareds Avatar asked Dec 27 '22 21:12

jareds


1 Answers

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();
    }
}
like image 57
Tudor Avatar answered Dec 29 '22 12:12

Tudor