anirban
anirban

Reputation: 704

Why this iterator is not working in foreach loop?

I am trying to create my own iterator and use this inside a foreach loop. But getting an error that Object can't be Converted from Object to Integer. Purpose of this code to understand iterator interface.

package com.java.collections;

import java.util.Iterator;

public class Counter implements Iterable {

    int count;

    Counter(int count){
        this.count = count;
    }

    @Override
    public Iterator iterator() {
        // TODO Auto-generated method stub
        return new Iterator<Integer>() {
        private int i = 0;
        @Override
        public boolean hasNext() {
            // TODO Auto-generated method stub

            return i < count;
        }

        @Override
        public Integer next() {
            // TODO Auto-generated method stub
            i++;
            return i;
        }

        @Override
        public void remove() {
            // TODO Auto-generated method stub

        }
    };

    }
}

package com.java.collections;

public class TestCounter {

    public static void main(String[] args) {
        new TestCounter().test();
    }

    void test() {
        for(Integer i : new Counter(5))
        {

        }
    }
}

Upvotes: 0

Views: 202

Answers (3)

Thorn
Thorn

Reputation: 4057

The Iterable interface can user generics and since your counter is an integer, you should specify this:

 public class Counter implements Iterable<Integer> {
    //other methods and code omitted

    public Iterator<Integer> iterator() {
        //same code as in posted question
    }
 }

Upvotes: 2

newuser
newuser

Reputation: 8466

for each requires only array or Iterable

Take a look The enhanced for statement

Upvotes: 0

Jeff Storey
Jeff Storey

Reputation: 57182

You have to use a generic type with iterable (Integer in your case)

public class Counter implements Iterable<Integer> {
...
}

Upvotes: 2

Related Questions