user3280874
user3280874

Reputation: 35

Java Explicit iterator works. Implicit forloop yields "Can only iterate over an array or an instance of java.lang.Iterable"

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

Upvotes: 0

Views: 2495

Answers (1)

rgettman
rgettman

Reputation: 178303

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) {

Upvotes: 4

Related Questions