Monday, 26 August 2013

TreeSet and compareTo() method. Single sort or multiple sorts

TreeSet and compareTo() method. Single sort or multiple sorts

Im currently working on a program, where im using a TreeSet to store
unique keys. I'm using a TreeSet, because I want them sorted.
As of now, I have been making a TreeSet object, and added the strings
one-at-a-time, when needed.
TreeSet set = new TreeSet();
set.add("How");
set.add("Are");
set.add("You");
Supposedly, the TreeSet uses the compareTo method in the Compareable
interface, to sort the strings. That would mean that the TreeSet would
have to do a sort each time I add a String to it.
Now my question is this: Would it be more efficient to create a HashSet
and then create the TreeSet after all strings are added to the HashSet?
TreeSet<String> treeSet = new TreeSet<String>(set);
My thoughts are going about whether the TreeSet would only need to do a
single sort that way.
Thanks in advance

No comments:

Post a Comment