您的位置:首页 > 移动开发 > Android开发

Android Java List 排序

2014-02-15 21:55 417 查看
原文章转自网上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) 与J***A Collections.sort(List<T> list)

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

注意说明:


Android的 Collections.sort()
与J***A的 Collections.sort() 是 一样的?

http://www.eoeandroid.com/thread-170969-1-1.html


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

http://m.blog.csdn.net/blog/lfdfhl/9263975


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

http://trinea.iteye.com/blog/1248517

日期比较
http://bbs.csdn.net/topics/350096002
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: