Two methods in [java.util.Collection](<https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html>)
create an array from a collection:
[Object[] toArray()](<https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#toArray-->)
[<T> T[] toArray(T[] a)](<https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#toArray-T:A->)
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 collection or bigger, it
// will be populated with collection values and returned (new array
// won't be allocated)
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):
Object[] toArray()
uses vectorized arraycopy
, which is much faster than the type-checked arraycopy
used in T[] toArray(T[] a)
.T[] toArray(new T[non-zero-size])
needs to zero-out the array at runtime, while T[] toArray(new T[0])
does not. Such avoidance makes the latter call faster than the former. Detailed analysis here : Arrays of Wisdom of the Ancients.Starting from Java SE 8+, where the concept of [Stream](<http://stackoverflow.com/documentation/java/88/streams/383/using-streams>)
has been introduced, it is possible to use the Stream
produced by the collection in order to create a new Array using the [Stream.toArray](<https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#toArray-java.util.function.IntFunction->)
method.
String[] strings = list.stream().toArray(String[]::new);
Examples taken from two answers (1, 2) to Converting ’ArrayList to ‘String[]’ in Java on Stack Overflow.