Search code examples
javaarraysstringtreeset

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


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.


Solution

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