Hi James Tedesco,
First of all, a warm welcome to CodeRanch!
James Tedesco wrote:I do not understand what this code does:
String[] stringArray = list.toArray(new String[0]);
specifically the new String[0] part.
The
toArray() method will (according to the
javadoc of the
Collection interface) return an array containing all elements in this collection. And this method comes in two versions: one version without parameters and another one with an array parameter.
The first version will return an
Object array containing all elements of this list. Here's a code example
So the return type of this method is
always Object[]. But what if you want to convert the list of
Strings into a
String array? Enter the second version of this method (with the array parameter). It lets you define the runtime type of the array to contain the collection elements. If you create an array which is not big enough to store all collection elements, a new array will be created at runtime to store the collection elements. Consider this code snippet
So from the output of
line4, you clearly see that a different array is created. And
new String[0] is the code to create an empty array, so
is the short-hand syntax for
Now let's see what happens if the array parameter is big enough to hold all collection elements
And if you run this code, you get the following output:
true
[one, two, three, null, six, five, four, three, two, one]
[one, two, three, null, six, five, four, three, two, one]
So two important things to note: if the array is big enough to store all collection elements, no other array is created and thus the array used as a parameter is the same as the array returned by the
toArray() method. If the array has more elements than the collection, the element in the array immediately following the end of the collection is set to
null.
Hope it helps!
Kind regards,
Roel
PS. Please always
QuoteYourSources and please note that many OCAJP8 study guides are currently available, so only mentioning a page number is not enough.