[ACCEPTED]-Java - Most efficient way to convert a TreeSet<String> into a String[]?-treeset

Accepted answer
Score: 21
String[] result = myTreeSet.toArray(new String[myTreeSet.size()]);


Score: 3

When using toArray() the following happens: a new 10 Object array is being allocated by using 9 new Object[size] and each element from the array will be 8 a reference to one of your strings element. Even 7 if actually points to strings, it's an array 6 with the type Object.

When using toArray(T[] a) the following 5 happens: a new T arrays is being allocated 4 by using

              .newInstance(a.getClass().getComponentType(), size) 

and each from the array will be 3 a reference to one of your strings because 2 a.getClass().getComponentType will return String.class in your case. This time, it's 1 an array with the type String.

More Related questions