aspose file tools*
The moose likes Java in General and the fly likes Getting a typed Iterator for Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Getting a typed Iterator for Generics" Watch "Getting a typed Iterator for Generics" New topic
Author

Getting a typed Iterator for Generics

Robert Darling
Ranch Hand

Joined: Jun 21, 2008
Posts: 100

public void checkUp(List<? extends Animal> animalList )
{
Iterator t=animalList.iterator();
while(t.hasNext())
{
Animal a=(Animal) t.next(); <------ Problem is herer
a.doCheckUp();
}
}

I know that the animalList can only contain animals. How can i make the iterator generic so that i don't have to cast t.next() into a animal.

Thank You
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Declare the iterator to be generic, just like you did the list--although it's cleaner to just use the foreach syntax.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575



but, this way of iterating is legacy way. Use enhanced for loop .
This looks cool


<edit>Iterator<Animal> to Iterator<? extends Animal> </edit>

hth
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

Iterator<? extends Animal>


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

David has been beaten me
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19719
    
  20

Seetharaman Venkatasamy wrote:but, this way of iterating is legacy way.

Not necessarily. If you need the Iterator (mostly to remove elements while iterating) it's still the way to go.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Getting a typed Iterator for Generics