Wednesday, April 23, 2014

Learning Java - What is "new String[0]"?

I came across some code as:

row.add( row.toArray( new String[0] ) );

But, what does "new String[0]" mean?

I found some good answers at the following (StackOverflow site):

According to my code, since my "row" object is not a granddaddy Java type Object but a String type, I want to add a row of String type to the existing row(s). By telling the method .toArray() to return reference type of String and not Object, my row will add a new array of Strings. By passing '0' into the String array, we are declaring to return the type only.

Here's a combined answer taken from folk at StackOverflow:
It is the array into which the elements of the Set are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
So that, in this example, you get back a String[]. The one without any argument gives back to you an Object[].
See you have 2 versions of this method:
By passing String[] array, you are using the generic version.
Object[] toArray(), returns an Object[] which cannot be cast to String[] or any other type array.
T[] toArray(T[] a) , returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array. If the set fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this set.



No comments:

Post a Comment