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

22,996

Solution 1

String[] result = myTreeSet.toArray(new String[myTreeSet.size()]);

Solution 2

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

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

java.lang.reflect.Array
              .newInstance(a.getClass().getComponentType(), size) 

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

Share:
22,996
Tim
Author by

Tim

Updated on February 13, 2020

Comments

  • Tim
    Tim over 4 years

    I was doing this:

    (String[]) myTreeSet.toArray();
    

    but that gives me a ClassCastException at runtime.

    The only thing I can think of doing is just making an array first and then iterating through each element in myTreeSet and adding it to the array. It seems like there must be a better way than this. Is there or should I just do this?

    Thanks.