Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting a typed Iterator for Generics

 
Robert Darling
Ranch Hand
Posts: 100
Android Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Iterator<? extends Animal>
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
David has been beaten me
 
Rob Spoor
Sheriff
Pie
Posts: 20667
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic