Hello, I have a doubt about generics usage with the iterator
interface.
The following declarations should be 'equivalent', I mean, all the
methods return the same type (a reference to Object):
Iterator it;
Iterator<Object> it;
Well, now consider the following code:
Vector<Animal> v;
...
Iterator<Object> it = v.iterator();
It doesn't work, since v.iterator() returns a Iterator<Animal>
reference, which is incompatible with Iterator<Object>,
but:
Vector<Animal> v;
...
Iterator it = v.iterator();
It works fine, but v.iterator() returns an Iterator<Animal> reference,
why are both references compatible??
TIA
hiwa - 10 Feb 2007 23:14 GMT
> Hello, I have a doubt about generics usage with the iterator
> interface.
[quoted text clipped - 22 lines]
>
> TIA
Try Iterator<? extends Object> it
Lew - 11 Feb 2007 06:11 GMT
> Hello, I have a doubt about generics usage with the iterator
> interface.
[quoted text clipped - 3 lines]
> Iterator it;
> Iterator<Object> it;
They are not equivalent. The first is a raw type and the second is a generic type.
> Vector<Animal> v;
> ...
[quoted text clipped - 10 lines]
> It works fine, but v.iterator() returns an Iterator<Animal> reference,
> why are both references compatible??
They aren't, really. You would get an "unchecked" warning, but it is
reluctantly permitted because Iterator is the erasure of all parametrized
Iterator types. You should avoid using raw types and generic types in the same
expressions, except for the few places where Java pretty much forces you to.
Read the Java Language Specification on these topics.
-Lew