Collection.sort()和通过添加到TreeSet获取排序集合之间的区别? [英] Difference between Collections.sort() and getting a sorted collection by adding into a TreeSet?

查看:776
本文介绍了Collection.sort()和通过添加到TreeSet获取排序集合之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 Set<Student> ts = new TreeSet<Student>();

    for(Student s : studentInfo){
         ts.add(s);
    }

    System.out.println(ts);

我在上面的代码片段中写了一个case块,对象。
我的问题是:使用这种方法和使用 Collections.sort(); 方法有什么区别。

I've written this above snippet in one of my case block in order to sort a collection of Student Objects. My question is: What is the difference between using this approach and using Collections.sort(); method.

推荐答案

不同之处在于 TreeSet Collections.sort()方法会在您调用 Set 时调整该方法。

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.

Collections.sort()的时间复杂度为 O(n * log(n)),而 TreeSet add()的复杂度为 log(n)。如果你使用相同大小的数据,那么 TreeSet 的复杂性将是相同的,因为你重复 add 操作 n 次。

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.

所以你只需要决定是否需要设置始终排序或在某个时间点排序。如果你的代码中有一个case,当你不需要排序,那么你不需要 TreeSet ,但如果你总是需要它排序,那么你应该使用 TreeSet

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!

另一个警告:由于其他人提到 TreeSet 只能取1 Comparator while您可以向 Collections.sort()提供不同的 Comparator 。因此取决于您的使用。您应该向我们提供有关您的用例的更多信息,以便给您一个彻底的答案。

Another caveat: As others mentioned TreeSet can only take 1 Comparator while you can supply different Comparators 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.

这篇关于Collection.sort()和通过添加到TreeSet获取排序集合之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆