The difference is that a TreeSet
keeps you data sorted at all times while the Collections.sort()
method sorts it when you call the method on your Set
.
The time complexity of Collections.sort()
is O(n*log(n))
while the TreeSet
's add()
's complexity is log(n)
. If you use the same size of data then the complexity in the TreeSet
's case will be the same because you repeat the add
operation n
times.
So you only have to decide whether you want your Set
ordered at all times or just at some point. If there is a case in your code when you don't need sorting then you don't need TreeSet
but if you will always need it to be sorted then you should use TreeSet
.
Please keep in mind that if you want to sort your Set
you have to create a List
from it first which might introduce some overhead!
Another caveat: As others mentioned TreeSet
can only take 1 Comparator
while you can supply different Comparator
s to Collections.sort()
. So it depends on your usage. You should give us more information on your use case in order to give you a thorough answer.