Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

Jon-Ryan Maloney
Jon-Ryan Maloney
5,704 Points

Struggling to understand Java arrays

I'm struggling to understand this logic from the Java arrays workshop:

String[] names = {"Ben", "Jerry", "Geoff", "Ryan"};

Cow[] cows = new Cow[names.length];

for (int i = 0; i < (names.length); i++) {
  cows[i] = new Cow(names[i]);
}

for (Cow cow : cows) { 
  console.printf("%s%n",
                 cow.getName());
}

Why did we declare a new array of Cows if we already did with the String array above it? Why isn't that redundant?

Also, why did we need to use two for loops?

Lukas Baumgartner
Lukas Baumgartner
14,817 Points

I've not watched the video, but:

Why did we declare a new array of Cows if we already did with the String array above it?

I guess it's just to show how things work. You maybe won't do it that way in a "real" program.

Also, why did we need to use two for loops?

Also just a guess, but I think they just want to let you know about the kinds of for loops you can use on arrays. The first one is a "normal" counting for loop, nothing special about it. The second one is an enhanced for loop, you can read it out loud kind of that way: for each Cow in the cow array, do something

Maybe you find this interessting: https://stackoverflow.com/questions/11555418/why-is-the-enhanced-for-loop-more-efficient-than-the-normal-for-loop

1 Answer

Jon-Ryan Maloney
Jon-Ryan Maloney
5,704 Points

Thanks Lukas. I just got overwhelmed with the multiple steps that didn't seem necessary. I'll check out your link.