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 Java Data Structures - Retired Exploring the Java Collection Framework Lists

Arnold Rosario
Arnold Rosario
16,357 Points

How come fruit.toArray(new String[0]); creates a new filled array of 3 elements?

I thought that since array size is locked at creation, and this specifies a single element array (since String[0] means first position), how can it possibly cause fruit.toArray(new String[0]) to create a filled 3 element array?

1 Answer

Gavin Ralston
Gavin Ralston
28,770 Points

He mentions the syntax is super-weird, and it's because of the way that toArray() works.

Here's the Collections.toArray() documentation, which is kind of obtuse, because that's how documentation gets the closer you get to the bare metal of the operating system/system architecture :)

fruit.toArray(new String[0]);

So, the toArray() function that all Collections must have returns an Object array (Object[])

Objects (like, the actual Object Object, the Top Type, the Thing Which All Others Subclass) can't be downcast to anything else, because they're.... not anything else. :)

Since you want to have an array of Strings, they graciously overloaded toArray to accept a parameter, and that's the type of array you want it to be. That parameter (argument) is a new array of the type you want. In this case, a String array.

So look at each part separately...

String[] someWords;   // that creates a reference to a String array, not an array itself, right?

String[] neededArrayType = new String[0];  // that creates a new String array of the type I want

someWords = someCollection.toArray(neededArrayType);

So what we're doing is setting up the variable to "hold" the array (someWords) and then calling someCollection's .toArray() method. We're feeding it the array we want to store it in (neededArrayType) but if it's not the right size, it'll create a new one of the right type for us so the collection can plug all of its values into it.