免费注册 查看新帖 |

Chinaunix

广告
  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1585 | 回复: 0
打印 上一主题 下一主题

java.util.Collections.sort(List list)与Comparable,C [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-07-12 20:51 |只看该作者 |倒序浏览

调用java.util.Collections.sort(List list)方法来进行排序的时候,
List内的Object都必须实现了Comparable接口。
否则出现下面的错误:
java.lang.ClassCastException
at java.util.Arrays.mergeSort(Arrays.java:1152)
at java.util.Arrays.sort(Arrays.java:1079)
at java.util.Collections.sort(Collections.java:113)

或者调用
java.util.Collections.sort(List list,Comparator c),
可以临时声明一个Comparator 来实现排序。

Comparable接口的 public int compareTo(Object arg0) {]
返回值大于0,则this被排在后面。arg0放在前面。
可以参看Integer 的compareTo()方法:

    public int compareTo(Integer anotherInteger) {
int thisVal = this.value;
int anotherVal = anotherInteger.value;
return (thisVal
返回值>=0,则不调用Arrays.swap(Object x[], int a, int b) 方法。

copyright © lizongbo
通过java.util.Collections.sort(List list,Comparator c)里临时声明的Comparator
可以方便的实现顺序或者倒序排列。
copyright © lizongbo
示例如下:
copyright © lizongbo
  Collections.sort(imageList, new Comparator() {
    public int compare(Object a, Object b) {
      int orderA = Integer.parseInt( ( (Image) a).getSequence());
      int orderB = Integer.parseInt( ( (Image) b).getSequence());
      return orderA - orderB;
    }
  });
如果需要改变排列顺序
copyright © lizongbo
改成return orderb - orderA 即可。
具体可以参考学习例子有:
copyright © lizongbo
http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#sorting

http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/TableSorter.java

http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/TableSorterDemo.java


copyright © lizongbo
这是一个实现了点击表格标题栏来实现表格数据排序的例子。

copyright © lizongbo
ps:  Collection(包括ArrayList等)的remove(Object o)方法
(src:java.util.AbstractCollection.java)
if (o.equals(e.next())) {
      e.remove();
使用的equals来判断的,而如果没有重写equals方法的话,
实际调用Object的
public boolean equals(Object obj) {
return (this == obj);
    }

因此,放进在集合里的元素,建议都重新实现自己的 equals方法。

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/38180/showart_338770.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP