3

I am writing a Java class that implements both Iterator and Iterable so it can be passed to a method taking either.

import java.util.Iterator;

public class Iterable<T> implements java.lang.Iterable, Iterator{  
    private Iterator<T> iterator;  
    public Iterable(java.lang.Iterable<? extends T> iterable){  
        this(iterable.iterator());  
    }  
    public Iterable(Iterator<? extends T> iterator){  
        this.iterator=iterator;  
    }  
    public Iterator<T> iterator(){  
        return iterator;  
    }  
    public boolean hasNext(){  
        return iterator.hasNext();  
    }  
    public T next(){  
        return iterator.next();  
    }  
}

On compilation, I get the following error:

Iterable.java:11: error: incompatible types: Iterator<CAP#1> cannot be converted to Iterator<T>  
            this.iterator=iterator;  
                          ^  
  where T is a type-variable:  
    T extends Object declared in class Iterable  
  where CAP#1 is a fresh type-variable:  
    CAP#1 extends T from capture of ? extends T  
1 error

Does anyone know what the problem is?

Circuit Craft
  • 184
  • 2
  • 8

0 Answers0