首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

聚合 List 排序

2012-10-27 
集合 List 排序list 排序实现和大家分享:以下是我做的一个实例:第一步:创建对象类:Content public class C

集合 List 排序
list 排序实现和大家分享:
以下是我做的一个实例:
第一步:创建对象类:Content

public class Content {

private String name;
private long time;

public Content(String name, long time){
this.name=name;
this.time=time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getTime() {
return time;
}
public void setTime(Long time) {
this.time = time;
}

}

第二步:创建一个排序规则(或根据那个属性来排):

ListSort类 不过要继承 Comparator 和 Serializable 接口
如果不继承 Serializable 接口 在用findbugs工具会报
Comparator doesn't implement Serializable

public class ListSort implements Serializable, Comparator {

public int compare(Object o1, Object o2) {
Content c=(Content) o1;
Content c2=(Content) o2;
if(c.getTime()<c2.getTime()){
return 1;
}else if(c.getTime()==c2.getTime()){
return 0;
}else{
return -1;
}

}



}

第三步:创建一个测试类:
Test
public class Test {

/**
* @param args
*/
public static void main(String[] args) {
List li=new ArrayList();
li.add(new Content("wang",123456l));
li.add(new Content("wang1",1234567l));
li.add(new Content("wang2",1299565l));
li.add(new Content("wang3",1234569l));

Comparator a=new ListSort();
Collections.sort(li,a);

for (int i = 0; i < li.size(); i++) {
Content c =(Content) li.get(i);
System.out.println(c.getName()+"==="+c.getTime());
}

}

}


结果为:
wang2===1299565
wang3===1234569
wang1===1234567
wang===123456

热点排行