Using toArray(T[] a) method to get Array
JDK 5.0 and above have come up with a convenient method to extract Array from a Collection without typecasting
<T> T[] toArray(T[] a)
The java doc says “Returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.”
Usage :
Assume you want o extract the arrays of gurus .
Collection<String> guruCollection = new ArrayList<String>();
There are multiple ways to do this but
String[] guru = guruCollection.toArray(new String[0]);
String[] guru = guruCollection.toArray((new String[] {});
String[] guru = guruCollection.toArray((new String[guruCollection.size() ]);
They both do the same job but which of the above method is more efficient ?
As per findbugs report , the most efficient way to do this is
String[] guru = guruCollection.toArray((new String[guruCollection.size() ]);
The code
String[] guru = guruCollection.toArray(new String[0]);
works well for concurrent or synchronized collections.
Form performance perspective , there is not a huge difference between them so I will prefer
String[] guru = guruCollection.toArray(new String[0]);








