原文章转自网上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
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
注意说明: