Java Generics, Cannot Convert from E to E
My code cannot convert from E to E. I can do a cast to type E but it seems redundant at t开发者_C百科his stage. My array is already declared as E-type.
import java.util.Iterator;
public class DataTypeDemo<E>
{
private E[] data = (E[]) new Object [10];
public MyIterator newIterator()
{
return new MyIterator();
}
private class MyIterator<E> implements Iterator<E>
{
private int location;
public boolean hasNext()
{
return location < data.length;
}
public E next()
{
return (data[location++]); // error here
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
}
Compiler, throws this error:
DataTypeDemo.java:23: incompatible types found : E required: E
Your inner type introduces it's own type variable:
private class MyIterator<E /* this is the problem*/> implements Iterator<E>
And thereby overwrites the outer class type variable
Change your type declaration to this:
private class MyIterator implements Iterator<E>
Reference:
- Generics FAQ (although this problem is not mentioned literally, it is implied by this FAQ entry)
The root of your problem is that an inner class of yours. For the compiler, there are no guarantees that the two E's are of the same type.
import java.util.Iterator;
import java.util.ArrayList;
public class DataTypeDemo<E>
{
private ArrayList<E> data = new ArrayList<E>(10);
private class MyIterator implements Iterator<E>
{
private int location;
public boolean hasNext()
{
return location < data.size();
}
public E next()
{
return data.get(location++);
}
public void remove()
{
throw new UnsupportedOperationException();
}
}
}
Though once you are aware of the problem, feel free to implement your own solution ;)
Happy hacking.
That's because you've given the inner class MyIterator
its own type parameter E
. Note that that E
is a different type parameter than the E
of the enclosing class (you've named them both E
, but they are two different type parameters).
Just leave off the type parameter for the inner class:
private class MyIterator implements Iterator<E> {
I think that the problem is that your nested iterator type is defined as a generic class also parameterized over an unrelated type named E. To fix this, change
private class MyIterator<E> implements Iterator<E>
To
private class MyIterator implements Iterator<E>
This first declaration says that the iterator for your type can be parameterized over any type, not just the type of the outer container. It also introduces a new type variable called E that is separate from the E in the outer declaration. This second definition says that the for any container type, there is one iterator type that isn't generic with respect to the outer type. This is probably what you intended.
精彩评论