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 trialMatthew Francis
6,967 PointsWhat does the number in fruit.toArray[0] represent?
Documentation:
https://docs.oracle.com/javase/7/docs/api/java/util/List.html
Code:
List<String> fruit = new ArrayList<String>();
fruit.add((String) "pear");
fruit.add((String)"avocado");
System.out.printf("%s %n", fruit);
String[] newFruit = fruit.toArray(new String[0]);/*This means "turn the Array(a String array) into a string array", but what does the number represent inside the []? I tried to read the documentation but I'm still puzzled*/
1 Answer
Evan Demaris
64,262 PointsHi Matthew,
In String[] newFruit = fruit.toArray(new String[0])
the new String[0]
is there to ensure that the correct type of object is returned. If the array is initialized to the wrong size, it's replaced with an array of the same type with the correct size by toArray()
.
Ideally, you would prevent the code from having to replace anything to maximize efficiency, and use something like String[] newFruit = fruit.toArray(new String[fruit.size()]);
Hope that helps!
J.D. Sandifer
18,813 PointsJ.D. Sandifer
18,813 PointsEvan, it probably doesn't take long to check if the new array of size 0 is large enough to hold the elements from the list newFruit since any non-empty list would make it too small. Remember to avoid Premature Optimization.
However, I would agree with your suggested code based on code readability - it's much easier to understand what's happening there with your change. Thus saving precious brain power and time for whoever else has to look at the code. (And preventing or pre-answering questions like the one that started this conversation. Bravo!)