Creating an Array from a Collection

suggest change

Two methods in java.util.Collection create an array from a collection:

Object[] toArray() can be used as follows:

Set<String> set = new HashSet<String>();
set.add("red");
set.add("blue");

// although set is a Set<String>, toArray() returns an Object[] not a String[]
Object[] objectArray = set.toArray();

<T> T[] toArray(T[] a) can be used as follows:

Set<String> set = new HashSet<String>();
set.add("red");
set.add("blue");

// The array does not need to be created up front with the correct size.
// Only the array type matters. (If the size is wrong, a new array will
// be created with the same type.)
String[] stringArray = set.toArray(new String[0]);  

// If you supply an array of the same size as the collection, or bigger, it
// is populated and returned (no new array is allocated). If the array is
// bigger, the element immediately after the collection is set to null.
String[] stringArray2 = set.toArray(new String[set.size()]);

The difference between them is more than just having untyped vs typed results. Their performance can differ as well (for details please read this performance analysis section):

Starting in Java SE 8, when Stream was introduced, the collection's stream can create a new array with Stream.toArray:

String[] strings = set.stream().toArray(String[]::new);

Examples taken from two answers (1, 2) to Converting ’ArrayList to ‘String[]’ in Java on Stack Overflow.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents