5

what is fundamental difference in these two following approach for converting collection to array object

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

 String[] array= iName.toArray(new String[iName.size()]);//1
 String[] array= iName.toArray(new String[0]);//2

when should use approach-1 and when approach-2?

1
  • I thought if you were instantiating a new String object you use () do define the parameters.
    – tim
    May 18, 2015 at 12:16

4 Answers 4

4

The first approach is better, since you create one array, and toArray uses it to store the elements of the input list. The second approach results in toArray creating another array, since it can't store anything in an empty array.

You will encounter a different behavior if you pass to the method an array whose length is larger than the size of the input list, since in that case, the size's element of the array (where size is the size of the input list) will be assigned null.

The only time it would make sense to pass to the method an array smaller than the size of the list is if you don't instantiate the array when calling the method, but use a pre-existing array :

array = iName.toArray(array);

Here you don't know in advance if array will be large enough to contain the elements of iName. If it isn't, toArray will return a new array. If it is, toArray will return the input array.

2

The difference between these two approaches:

    String[] array = iName.toArray(new String[iName.size()]);
    String[] array = iName.toArray(new String[0]);

is quite different if there is a possibility that the source collection (iName in this case) can be modified concurrently. If there is no possibility of concurrency, then the first line is preferable.

This doesn't strictly apply in your example, where the source collection is ArrayList, which is not thread-safe. But if the source collection is a concurrent collection, then the behavior under concurrent modification is significant. In this case, the first line has a race condition. The calling thread first gets the size; another thread might then add or remove an element, changing its size. But then the calling thread allocates the array with the old size and passes it to toArray.

This doesn't result in error. The cases are well-defined if you read the specification of Collection.toArray(T[]) carefully. If the collection had grown, a new array would be allocated for it, making the caller's array allocation redundant. If the collection had shrunk, the tail of the array would end up with null elements. This isn't necessarily an error, but any code that consumes the resulting array has to be prepared to handle nulls, which may be unpleasant.

Passing a zero-length array avoids these issues, at the possible cost of allocating a useless zero-length array. (One could keep a cached version around, but it adds clutter.) If the collection is empty, the zero-length array is simply returned. If the collection has elements, though, the collection itself allocates the array of the correct size and fills it. This avoids the race condition of the caller handing in an array of the "wrong" size.

In the Java 8 Streams API, the Stream.toArray method avoids this issue by having the caller pass in an array factory. This lets the caller specify the type but allows the collection to specify the proper size. This hasn't yet been retrofitted to Collections though. This is covered by an RFE JDK-8060192.

0

If you look at the implementation you can understand the difference:

public <T> T[] toArray(T[] a) {
        if (a.length < size)
            // Make a new array of a's runtime type, but my contents:
            return (T[]) Arrays.copyOf(elementData, size, a.getClass());
        System.arraycopy(elementData, 0, a, 0, size);
        if (a.length > size)
            a[size] = null;
        return a;
    }

If you supply an array smaller than the ArrayList, a new array gets created. If the supplied array is larger then the ArrayList, it will be used to copy the content of the list's backing array.

In terms of performance the best practice would be using the first approach (iName.toArray(new String[iName.size()])), but the penalty for the second approach is not great (a 0 sized array being created).

I personally use the second approach, since I think it makes the code more readable.

0

Basically both approaches do the same thing and will produce identical outputs, but under the hood they behave a little bit different.

In first approach since the array's size is big enough List can copy its items to the Array and returns the same one. When you use second approach what List class do is almost exactly to your first approach: create a new Array with correct size to copy the values.

From efficiency perspective: in first approach, one Array is created and not used which is not a good thing even is creating an Array won't take much time or processing power but it is redundant and should not be done. If you know the size of the List,all collections know their size, you should use the first approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.