According to java doc for toArray() Returns an array containing all of the elements in this collection.
and toArray(Object obj[]). Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
first toArray() i understand but second toArray(Object obj[]) i can't understand.Please explain with example.
The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input. The array operations allow the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object .
The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.
ToArray(Type)Copies the elements of the ArrayList to a new array of the specified element type. public: virtual Array ^ ToArray(Type ^ type); C# Copy.
One is generic, the other isn't. toArray()
will return Object[]
while toArray(T[])
will return an array of type T[]
.
Sample:
public static void main(String[] args) {
Object[] baseArray = new ArrayList<String>().toArray();
System.out.println(baseArray.getClass().getCanonicalName());
String[] improvArray = new ArrayList<String>().toArray(new String[5]);
System.out.println(improvArray.getClass().getCanonicalName());
}
Output:
java.lang.Object[]
java.lang.String[]
First of all, the second method is toArray(T[] a)
instead of toArray(Object[] a)
. The T
in the first function header is called a type parameter, which means that the actual class it is referring to changes depending on how you call the method. The type parameter can be used by the toArray
method to do things using the type T
, without knowing what T
actually is.
In this example, T
would be String
:
x.toArray(new String[0])
In this example, T
would be Integer
:
x.toArray(new Integer[0])
In this example, T
would be MyClass
:
x.toArray(new MyClass[0])
The method toArray(T[] a)
uses the provided type information to return an array of the given type. For example, the first example would return an array of type String
, while the second example would return an array of type Integer
.
As a result, a call to toArray()
produces the same result (An array of Object
) as a call to toArray(new Object[0])
.
For more information on generics, you can have a look at this tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With