java.util.Collections的方法sort(List list,Comparable co),请问这是怎么用的阿?

lilyjk2003 2005-04-21 02:53:35
我看到java.util.Collections有关于排序的方法sort(List list,Comparable co),请问其中的Comparable参数要怎么用?最好给个例子。谢谢了
...全文
722 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Voxer 2005-04-21
  • 打赏
  • 举报
回复

String[] sArray = new String[]{"z","a",C"};
List list = Array.aslist(sArray);

Collection.sort(list);//结果为C a z
Collection.sort(list,String.CASE_INSENSITIVE_ORDER);//结果为a C z
Collection.sort(list,Collections.reverseOrder());//z,a,C
Collection.sort(list,String.CASE_INSENSITIVE_ORDER);
Collection.reverse(list);//z,C,a


jFresH_MaN 2005-04-21
  • 打赏
  • 举报
回复
public static void sort(List list,
Comparator c)Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. The specified list must be modifiable, but need not be resizable. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.

第二参数是comparator,这是一个接口,我们必须实现这个接口里面的compare方法
所以里面传的参数就是一个类,实现comparator接口的类
因为排序的原理就是比较两个元素,然后根据排序规则返回两个数怎么排位置,我们写的compare()方法就是排序两个传进来的Object,也就是我们自定义的排序规则!

一般我们使用这个sort方法的时候,对于第二个参数都是采用匿名内部类的做法。

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧