RamanSB
RamanSB

Reputation: 1172

Transforming an ArrayList to an Array using toArray() method

Consider the following code:

 import java.util.*;

 public class ArrayQuestion{
        public static void main(String[] args){
               List<String> list = new ArrayList<>();
               list.add("Chocolate");
               list.add("Vanilla");
        //Converting the List to an Array
        Object[] objectArray = list.toArray();

So the toArray method returns an array of default type Object[]. Let's say I wanted to create a String array, I read that I would pass a string[] object in to the toArray method.

        String[] stringArray = list.toArray(new String[0]);

I read that the advantage of specifying a size of 0 for the parameter is that Java will create a new array of the proper size for the return value.

Could somebody please explain this, I looked up the toArray(String[] stringArray) method in the Java API. I still do not understand what return value the above statement is alluding too.

My question is specifically about parameter passed in to the toArray method and why it is 0 and how passing 0 creates an array of the proper size of the list.

Upvotes: 1

Views: 385

Answers (3)

Vojtěch Kaiser
Vojtěch Kaiser

Reputation: 568

Look into implementation of, for example, LinkedList

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(
                            a.getClass().getComponentType(), size);
    int i = 0;
    Object[] result = a;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;
    if (a.length > size)
        a[size] = null;
    return a;
}

the behaviour should be pretty clear from there.

Upvotes: 0

Joni
Joni

Reputation: 111329

When you pass an array that is too small to the toArray method, it creates an array of the same class but with the correct size. An empty array (length 0) is perfect for that.

Upvotes: 4

nanofarad
nanofarad

Reputation: 41281

The return value of the list will be assigned to stringArray. For example, if list contained 15 strings, then the invocation list.toArray(new String[0]) would return a String[] with 15 elements.

Here's a quote with more details, straight from the javadoc:

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list 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 list.

If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the collection is set to null. (This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)

Upvotes: 3

Related Questions