Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Collection.toArray() and Collection.toArray(Object obj[])

Tags:

java

arrays

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.

like image 972
App Kart Avatar asked Dec 01 '13 03:12

App Kart


People also ask

Why do you need toArray () method in the collection interface?

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 .

What is the use of toArray () in Java?

The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order.

What is toArray in C#?

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.


2 Answers

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[]
like image 142
Jeroen Vannevel Avatar answered Oct 12 '22 22:10

Jeroen Vannevel


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.

like image 33
Lorenz Avatar answered Oct 12 '22 22:10

Lorenz