use*_*097 5 java sorting collections comparator
如何ArrayList使用升序排序Comparator?我知道如何使用以下降顺序对其进行排序:
Comparator mycomparator = Collections.reverseOrder();
Run Code Online (Sandbox Code Playgroud)
然后
Collections.sort(myarrayList,mycomparator);
Run Code Online (Sandbox Code Playgroud)
只是想知道如何使用集合和比较器按升序对其进行排序?谢谢!
Cod*_*y S 22
把它扔到那里......你不能这样做:
Collections.sort(myarrayList);
Run Code Online (Sandbox Code Playgroud)
虽然已经有一段时间了......
使用默认版本:
Collections.sort(myarrayList);
Run Code Online (Sandbox Code Playgroud)
当然,这要求您的元素实现Comparable,但对于您提到的版本也是如此.
顺便说一句:您应该在代码中使用泛型,这样如果您的类没有实现Comparable,就会遇到编译时错误.编译时错误比运行时错误要好得多.
List<MyClass> list = new ArrayList<MyClass>();
// now fill up the list
// compile error here unless MyClass implements Comparable
Collections.sort(list);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
99041 次 |
| 最近记录: |