papantonis
papantonis

Reputation: 115

Is it possible to extend the functionality of an iterator in Java?

I was wondering if there is a way to extend the functionality of the iterator interface. Suppose that we have a Class that implements the Iterable interface (in the example above, instead of the overridden functions of the Iterator interface I have added myFunction).

public class MyClass implements Iterable{

    @Override
    public Iterator iterator() {
        return new Iterator() {
            @Override
            public boolean hasNext() {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public Tuple next() {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Not supported yet.");
            }
            public void myFunction(){

            }
        };
    }
}

If I put this code in another function I get compilation error ("cannot find symbol") and I was wondering why this happens.

public void anotherFunction(){
    MyClass a = new MyClass();
    a.iterator().myFunction();
}

Upvotes: 3

Views: 5903

Answers (3)

kan
kan

Reputation: 28951

Yes, of course. You could create another interface:

interface MyBetterIterator extends Iterator
{
    void myFunction();
}

then make the method return your type:

public class MyClass implements Iterable{

    @Override
    public MyBetterIterator iterator() {
...
    }
}

The feature is called "return type covariance", introduced in Java 5.

Upvotes: 10

Mike Clark
Mike Clark

Reputation: 11959

Even though you have added a function of your own to the Iterator instance, all you have told the classes that consume your class is that you are returning an Iterator. This means you are limited to the signature that the Iterator interface exposes. If you want access to the myFunction, you will have to formally declare your own interface that extends Iterator and then make your iterator() function return that instead. However, this will also break the Iterable contract, so you have to make that choice.

Upvotes: 2

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279910

Your myFunction() doesn't belong to the Iterator interface and therefore cannot be used on an Object declared with the type Iterator.

a.iterator().myFunction();
  ^
  Returns an Iterator and therefore gives a compilation error

Upvotes: 0

Related Questions