-5

How can i put this code into Generic form ?

List aviary = new ArrayList();
Eagle any Eagle;
aviary.add(new Eagle(100, "Brutus"));
aviary.add(new Eagle(100, "Chronos"));
for (int i=0; i<aviary.size(); i++) {
anyEagle = (Eagle) aviary.get(i);
anyEagle.hunt();
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130

2 Answers2

1

You can use generics and the for-each loop like this in Java 7

List<Eagle> aviary = new ArrayList<>();
aviary.add(new Eagle(100, "Brutus"));
aviary.add(new Eagle(100, "Chronos"));

for (Eagle eagle: aviary)
    eagle.hunt();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

First line needs to be changed to

List<Eagle> aviary = new ArrayList<>();

I assume Eagle is a valid object that you have. If you change the line above, you can get rid of the typecasting in this line

anyEagle = (Eagle) aviary.get(i);
Hirak
  • 3,601
  • 1
  • 22
  • 33