Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enhanced For Loop - Array of Objects

Ok so I have a class called Dog() which takes two parameters, a string and an integer.
This class has a method called bark(), which prints a string depending on the integer passed into the Dog() constructor.

I also have a class called Kennel() which creates an array of 5 Dog()s... looks like this:

public class Kennel
{
    Dog[] kennel = new Dog[5];
    public Kennel()
    {
        kennel[0] = new Dog("Harold",1);
        kennel[1] = new Dog("Arnold",2);
        kennel[2] = new Dog("Fido",3);
        kennel[3] = new Dog("Spot",4);
        kennel[4] = new Dog("Rover",5);
    }
}

For starters, this works, but seems wrong. Why do I have to start with Dog[] ... new Dog[5]? Maybe stupid question... I'm new to this.

Anyway... What I have been asked to do is use the "enhanced" for loop to iterate through the array calling bark().

So with a traditional for loop it would look like this:

for (i=0;i<kennel.length;i++)
{
    kennel[i].bark();
}

Simple stuff, right? But how do I implement this using the for(type item : array) syntax?

like image 976
MHz Avatar asked Mar 02 '12 09:03

MHz


People also ask

Can you use enhanced for loop on array?

Use the enhanced for each loop with arrays whenever you can, because it cuts down on errors. You can use it whenever you need to loop through all the elements of an array and don't need to know their index and don't need to change their values.

Can you use enhanced for loop on 2D array?

Since 2D arrays are really arrays of arrays you can also use a nested enhanced for-each loop to loop through all elements in an array.

Does enhanced for loops traverse the complete array sequentially?

3) The enhanced for loop can only iterate in incremental order.

Which is a limitation of an enhanced for loop?

The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order. Here, you do not have the option to skip any element because it does not work on an index basis. Moreover, you cannot traverse the odd or even elements only.


1 Answers

Just use it in the for each

for(Dog d : kennel) {
    d.bark();
}
like image 186
Tristian Avatar answered Oct 14 '22 00:10

Tristian