Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / February 2007

Tip: Looking for answers? Try searching our database.

About generics and Iterator

Thread view: 
Neroku - 10 Feb 2007 18:14 GMT
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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.