Mock tests, Interview questions, Tutorials and Tech news
 
 
Home > Programming / tutorials > Using toArray(T[] a) method to get Array

Using toArray(T[] a) method to get Array

December 29th, 2009 Vinay Leave a comment Go to comments

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]);

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Mixx
  • Google Bookmarks
  • IndianPad
  • Reddit
Categories: Programming / tutorials Tags:
  1. No comments yet.
  1. No trackbacks yet.
Get Adobe Flash playerPlugin by wpburn.com wordpress themes