0

I've implemented Iterable<> in my base class but the subclass will not allow an implicit forloop.

Why is the Iterator<> working correctly but the for-loop complaining of

Can only iterate over an array or an instance of java.lang.Iterable

I would have expected the Iterable<> interface to be visible in the subclass. What am I missing?

package tester;

import java.util.ArrayList;
import java.util.Iterator;

public class TestInher {

    private Concrete<Integer>   mList   = new Concrete<Integer>();

    public TestInher() {}

    public abstract class   Base<T>
        implements Iterable<T>
    {
        protected ArrayList<T>  list = new ArrayList<T>();

        @Override
        public Iterator<T> iterator() {return list.iterator();}

        public abstract void add(T item);
    }

    public abstract class   ClassAbstract<T> extends    Base<T>{}

    public class    Concrete<T>
        extends ClassAbstract<T>
    {
        @Override
        public void add(T item) {list.add(item);}
    }

    public void doIt() {
        for(int i=0; i<10; i++) {mList.add(i);}

        Iterator<Integer> i = mList.iterator(); 
        while (i.hasNext()) {
            System.out.println(i.next());
        }

        //Can only iterate over an array or an instance of java.lang.Iterable
        for(Integer i : mList.iterator()) {
        }
    }
}
  • `Iterator` is not `Iterable`. – Sotirios Delimanolis Feb 25 '14 at 17:55
  • Not a serious suggestion, but you could actually make your `Iterator` implement `Iterable` with an idempotent method `return this`. Then your code would actually work, even if meaninglessly so :) – Marko Topolnik Feb 25 '14 at 17:58
  • I'm trying to remember the oddity, but I'm recalling that, at least in some circumstances, an interface is not implicitly inherited by subclasses -- if you intend the interface to be supported you must explicitly state that in the subclass definition. – Hot Licks Feb 25 '14 at 18:17
  • Related: [Why is Java's Iterator not an Iterable?](http://stackoverflow.com/questions/839178/why-is-javas-iterator-not-an-iterable). – rgettman Feb 25 '14 at 20:40

1 Answers1

4

In the enhanced for loop, you iterate over the Iterable, not over the Iterator. The Iterable gets the Iterator that is implicitly used in this loop, but an Iterable is not itself the Iterator. Try the Iterable itself.

for (Integer i : mList) {
rgettman
  • 176,041
  • 30
  • 275
  • 357