Extended for Loop-array of objects

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

I also have a class called Kennel () that 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 it seems wrong. Why should I start with Dog [] ... new Dog [5]? Maybe a stupid question ... I'm new to this.

In any case ... What I was asked to do is use the "extended" loop to iterate through the array calling bark ().

So, with the traditional for the loop, it will look like this:

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

Simple things, right? But how to implement this with the syntax for (type item: array)?

+4
source share
3 answers

Just use it for everyone.

 for(Dog d : kennel) { d.bark(); } 
+18
source

Here's how you do it using advanced for loop.

 for(Dog dog : kennel) { dog.bark(); } 

For your other question, if you are going to use arrays, you will have to declare a size before you start adding elements to it. However, one exception is that you are initializing and declaring on the same line. For instance:

 Dog[] dogs = {new Dog("Harold", 1), new Dog("Arnold", 2)}; 
+10
source

About your second question: "Why should I start with Dog [] ... new Dog [5]?"

Because of the same logic you have to put Dog dog = new Dog (); ---- (1) This is why Dog [] dogArray = new Dog [5]; --- (2)

If you have no problems with the first, then why the carpet about the second.

0
source

Source: https://habr.com/ru/post/1399353/


All Articles