About generics and Iterator

N

Neroku

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
 
H

hiwa

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

Try Iterator<? extends Object> it
 
L

Lew

Neroku said:
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;

They are not equivalent. The first is a raw type and the second is a generic type.
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??

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top