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

Tim picture Tim · Feb 12, 2012 · Viewed 22.3k times · Source

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.

Answer

Louis Wasserman picture Louis Wasserman · Feb 12, 2012
String[] result = myTreeSet.toArray(new String[myTreeSet.size()]);