The difference is that a TreeSet allows TreeSet to sort data at all times, and the Collections.sort() method sorts it when you call the method on Set .
The time complexity of Collections.sort() is O(n*log(n)) , and the complexity of TreeSet add() is log(n) . If you use the same data size, the complexity in the case of TreeSet will be the same as you repeat the add n operation.
Thus, you only need to decide whether you want your Set be ordered at all times or only at some point. If there is a case in your code where you do not need sorting, you do not need a TreeSet , but if you always need to sort it, you should use a TreeSet .
Remember that if you want to sort a Set , you need to create a List first, which can lead to some overhead!
Another disclaimer:. As mentioned above, a TreeSet can only accept 1 Comparator , while you can provide different Comparator - Collections.sort() . So it depends on your use . You should provide us with more information about your use case in order to give you a comprehensive answer.
Adam Arold Sep 12 '13 at 9:45 on 2013-09-12 09:45
source share