Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 532
Tim Avatar asked Feb 12 '12 06:02

Tim


People also ask

How do I convert a char to a string?

To convert a char to a string in Java, the toString() and valueOf() methods are used. The toString() and valueOf() methods are both used to convert any data type to a string. For converting a char to a string, they both function identically.

How do you change the size of a TreeSet?

TreeSet. size() method is used to get the size of the Tree set or the number of elements present in the Tree set. Parameters: The method does not take any parameter. Return Value: The method returns the size or the number of elements present in the Set.

Is TreeSet already sorted?

TreeSet implements the SortedSet interface. So, duplicate values are not allowed. Objects in a TreeSet are stored in a sorted and ascending order. TreeSet does not preserve the insertion order of elements but elements are sorted by keys.


1 Answers

String[] result = myTreeSet.toArray(new String[myTreeSet.size()]);
like image 140
Louis Wasserman Avatar answered Oct 18 '22 20:10

Louis Wasserman