If an array variable v has type A[] , where A is a reference type, then v can hold
a reference to an instance of any array type B[] , provided B can be assigned to A
(§5.2). This may result in a run-time exception on a later assignment; see §10.5
for a discussion.
Campbell Ritchie wrote:
Did you read the documentation for List#toArray()? Did you see what its return type is? Did you see the strange design of its overloaded brother? For an exercise, see if you can find a version of that overloaded method for Java1.2 or Java1.3 or Java1.4 and see how it differs from the current version.
Is down casting allow here? String[] array2 = (String[]) list.toArray(); This returns an Object array.
I know that String[] array2 = list.toArray(new String[0]) works by specifying the String[] array as a parameter for toArray() method. And it will give you a String array.
My apologies; you obviously did look at the documentation.Jj Roberts wrote:. . . Henry noted that toArray(new String[0]) returns a String[] . . . .
Some of the details in the Java14 version are to be found in the JDK1.4 Collection#toArray page.toArray
public Object[] toArray()
Returns an array containing all of the elements in this list in proper sequence. Obeys the general contract of the Collection.toArray method.
Specified by:
toArray in interface Collection
Returns:
an array containing all of the elements in this list in proper sequence.
See Also:
Arrays.asList(Object[])
toArray
public Object[] toArray(Object[] a)
Returns an array containing all of the elements in this list in proper sequence; the runtime type of the returned array is that of the specified array. Obeys the general contract of the Collection.toArray(Object[]) method.
Specified by:
toArray in interface Collection
Parameters:
a - the array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.
Returns:
an array containing the elements of this list.
Throws:
ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this list.
NullPointerException - if the specified array is null.