Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Practice Java Arrays - why create a Cow[] ?

In the solution for Practice Java Arrays, the solution uses the syntax Cow[] cows = new Cow[names.length]. If I were populating with Cow objects, then making a new Cow makes more sense to me.

I solved it using String[] cows = new String[cowNames.length]. All we are really doing is copying strings between arrays in this practice.

Am I overlooking something or is this simply a style choice by the author?

Thanks!

2 Answers

Steven Parker
Steven Parker
231,261 Points

You didn't link to the course page, so I'm not sure what the structure of a "Cow" object is like, but certainly an array of Cows would be different from an array of Strings.

It could just be that in this exercise, nothing is done with them that would make the difference cause an error.


Update: Now that I've seen it, the "Cow" object is very simple and is just a container for the name string. But still, a complex object is very different from a string and the challenge instructions specifically called for creating an array of those objects.

But is is a very simple example, and the objects are not used in a way that would make it clear why they would be needed over just an array of name strings. You have to imagine that future expansions of the program would eventually make use of the difference.

Thank you. I follow what you are saying and appreciate that you took the time to answer.

Hi Steven,

Thank you and my apologies for not linking:.

Practice Java Arrays

Solution to Practice Java Arrays

Specifically I am referring to the Solution todo item 2 and the usage of

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

vs using

String[] cows = new String[cowNames.length]

Other than style is there are reason to use Cow[] , is it more correct than String[] here for some reason?