Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for-each loop can only iterate over an array or an instance of java.lang.Iterable [duplicate]

Tags:

java

The following code doesn't work. What's wrong with this code? Compiler complains in the for loop that NumberList isn't a Iterable class.

What kind of class can be used in for-each loop? How to make NumberList iterable? I tried making NumberList implement Iterable, but it doesn't seem to work because I don't know how to define the Iterator properly.

If someone could demonstrate how to make this code work, or link me to a tutorial that'd be great.

public class Test{
    public class NumberList{
        private int numItems;
        private Number[] numbers;

        public NumberList(int size){
            this.numbers = new Number[size];
            this.numItems=0;
        }

        public void add(Number n){
            this.numbers[this.numItems++]=n;
        }
    }

    public void printPairs() {
        ArrayList<Integer> num=new ArrayList<Integer>();

        NumberList numbers = new NumberList(50);
        numbers.add(4);
        numbers.add(5);
        numbers.add(6);

        for(Number n1: numbers){
            System.out.println(n1);
        }
    }
}
like image 899
turtlesoup Avatar asked Aug 25 '13 21:08

turtlesoup


People also ask

Can only iterate over an array or an instance of Java Lang iterable meaning?

The error can only iterate over an array or an instance of java. lang. iterable doesn't mean that it stops the user from using a loop on an array or an instance. It means that a loop is used that doesn't complement its conditions - for example, the for or foreach loop.


1 Answers

NumberList does not implement Iterable. As far as the compiler is concerned its just any other class.

You need to do something like this

public class NumberList implements Iterable<Number> {

    private int numItems;
    private Number[] numbers;

    public NumberList(int size) {
        this.numbers = new Number[size];
        this.numItems = 0;
    }

    public void add(Number n) {
        this.numbers[this.numItems++] = n;
    }

    @Override
    public Iterator<Number> iterator() {
        return Arrays.asList(numbers).subList(0, numItems).iterator();
    }
}
like image 124
sksamuel Avatar answered Nov 14 '22 22:11

sksamuel