Android Java List 排序

原文章转自网上blog,但是其中代码运行后原来的list排序根本没有改变。

于是打开Comparator文档看了,发现原代码的compare函数实现的返回值有问题!

修正后运行结果正确了,代码如下:

@SuppressWarnings("unchecked")
void test() {
ArrayList list = new ArrayList();
list.add(new Person("lcl 28", 28));
list.add(new Person("fx 23", 23));
list.add(new Person("wqx 29", 29));
list.add(new Person("qd 20", 20));
list.add(new Person("xgw 69", 69));
Comparator comp = new Comparator() {
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
if (p1.age < p2.age)
return -1;
else if (p1.age == p2.age)
return 0;
else if (p1.age > p2.age)
return 1;
return 0;
}
};
Collections.sort(list, comp);

for (int i = 0; i < list.size(); i++) {
Person p = (Person) list.get(i);
System.out.println(p.getName());
}
}

public static class Person {

private int age;
private String name;

public Person(String name, int age) {
this.age = age;
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
} www.2cto.com
@SuppressWarnings("unchecked")
void test() {
ArrayList list = new ArrayList();
list.add(new Person("lcl 28", 28));
list.add(new Person("fx 23", 23));
list.add(new Person("wqx 29", 29));
list.add(new Person("qd 20", 20));
list.add(new Person("xgw 69", 69));
Comparator comp = new Comparator() {
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
if (p1.age < p2.age)
return -1;
else if (p1.age == p2.age)
return 0;
else if (p1.age > p2.age)
return 1;
return 0;
}
};
Collections.sort(list, comp);

for (int i = 0; i < list.size(); i++) {
Person p = (Person) list.get(i);
System.out.println(p.getName());
}
}

public static class Person {

private int age;
private String name;

public Person(String name, int age) {
this.age = age;
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

http://www.2cto.com/kf/201112/115107.html

摘自 michaelpp的专栏

其他

android如何实现文件按时间先后顺序排列显示http://blog.csdn.net/sunnyfans/article/details/8957147

Android ListView中带有时间数据的排序

http://blog.csdn.net/zhenglingkun/article/details/8350507

android Collections.sort(List<T> list) 与JAVA Collections.sort(List<T> list)

http://blog.csdn.net/luhuajcdd/article/details/7533956


注意说明:

Android的 Collections.sort() 与JAVA的 Collections.sort() 是 一样的


Android利用Collections.sort()对HashMap里的键值对按照键进行排序

对象数组或list排序及Collections排序原理


日期比较


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值