0

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

        }
    }
}

3 Answers 3

2

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

public class Counter implements Iterable<Integer> {
...
}
Sign up to request clarification or add additional context in comments.

3 Comments

did that, got error as "Type mismatch: cannot convert from element type Iterable to Integer"
You are most likely trying to return the Iterator instead of the Integer in your next() method.
Yes Jeff, sorry I typed public class Counter implements Iterable<Iterable> in a hurry. Changed that back to Integer. And it worked. Thanks
2

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
    }
 }

Comments

0

for each requires only array or Iterable

Take a look The enhanced for statement

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.