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); // 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
T toArray(T a).
T toArray(new T[non-zero-size])needs to zero-out the array at runtime, while
T toArray(new T)does not. Such avoidance makes the latter call faster than the former. Detailed analysis here : Arrays of Wisdom of the Ancients.