原文章轉自網上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.aiwalls.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;
}
}
摘自 michaelpp的專欄