Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList.toArray() method in Java

Tags:

java

arrays

I am wondering why did they design the toArray method in ArrayList to take a input of an array in Java?

    ArrayList<String> listArray = new ArrayList<String>();

    listArray.add("Germany");
    listArray.add("Holland");
    listArray.add("Sweden");

    String []strArray = new String[3];
    String[] a = (String [])listArray.toArray(strArray);

To me it appears that, they dont need this input because the instance of the ArrayList itself has enough details to convert the data into an array.

My question is why do they still need the array to be passed in? Thanks.

like image 980
java_mouse Avatar asked Mar 26 '12 14:03

java_mouse


People also ask

What does toArray () do in Java?

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

How do you use the toArray set?

Set toArray() method in Java with Example If we provide the type of Object array we want we can pass it as an argument. for ex: set. toArray(new Integer[0]) returns an array of type Integer, we can also do it as set. toArray(new Integer[size]) where size is the size of the resultant array.

Can we change load factor of ArrayList?

Vector and ArrayList don't have a load factor.


2 Answers

Two reasons I can think of:

  1. Erasure means that the generic parameters aren't available at runtime, so an ArrayList<String> doesn't know that it contains strings, it's just the raw type ArrayList. Thus all invocations of toArray() would have to return an Object[], which isn't strictly correct. You'd have to actually create a second array of String[] then iterate over the first, casting all of its parameters in turn to come out with the desired result type.
  2. The way the method is defined means that you can pass in a reference to an existing array, and have this populated via the method. In some cases this is likely very convenient, rather than having a new array returned and then copying its values elsewhere.
like image 171
Andrzej Doyle Avatar answered Oct 29 '22 10:10

Andrzej Doyle


In your code, the ArrayList can contain anything, not only Strings. You could rewrite the code to:

ArrayList<String> listArray = new ArrayList<String>();

listArray.add("Germany");
listArray.add("Holland");
listArray.add("Sweden");

String []strArray = new String[3];
String[] a = listArray.toArray(strArray);

However, in Java arrays contain their content type (String) at runtime, while generics are erased by the compiler, so there is still no way for the runtime system to know that it should create a String[] in your code.

like image 29
Mathias Schwarz Avatar answered Oct 29 '22 10:10

Mathias Schwarz