Here's the indicted code :
import java.util.Iterator;
public class MyClass<T> implements Iterable<T> {
private int n;
private Object array[];
public myClass( int size ){
array = new Object[size];
n=0;
}
@Override
public Iterator<T> iterator(){
return new MyClassIterator<T>(n,array); //Here's my error!
}
}
class MyClassIterator<T> implements Iterator<T>{
private int n;
private T[] array;
MyClassIterator( int n, T[] array ){
this.n = n;
this.array = array;
}
@Override
public T next(){
return array[n++];
}
@Override
public boolean hasNext(){
return n==array.length;
}
}
This code give me the error :
error: incompatible types: Object[] cannot be converted to T[] return new myClassIterator(n,array); where T is a type-variable: T extends Object declared in class myClass Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error
But after removing the <T> in the creation of the myClassIterator object in iterator() the error disappears and the code works without problems, now I'm asking why specify the generic type give me this error?
The "correct" code that works would be this :
@Override
public Iterator<T> iterator(){
return new myClassIterator(n,array);
}