首页 > 编程语言 > 详细

ArrayList排序 降序排列

时间:2017-01-25 23:04:33      阅读:250      评论:0      收藏:0      [点我收藏+]
 1 public class Person {
 2     String name;
 3     int age;
 4     public Person(String name, int age) {
 5         this.name = name;
 6         this.age = age;
 7     }
 8     public int getAge() {
 9         return age;
10     }
11     public void setAge(int age) {
12         this.age = age;
13     }
14     public String getName() {
15         return name;
16     }
17     public void setName(String name) {
18         this.name = name;
19     }
20 }
21 import <a href="http://lib.csdn.net/base/17" class=‘replace_word‘ title="Java EE知识库" target=‘_blank‘ style=‘color:#df3434; font-weight:bold;‘>Java</a>.util.Comparator;
22 public class Mycomparator implements Comparator{
23     public int compare(Object o1,Object o2) {
24         Person p1=(Person)o1;
25         Person p2=(Person)o2;  
26        if(p1.age<p2.age)
27            return 1;
28        else
29            return -1;
30        }
31 }
32 import java.util.ArrayList;
33 import java.util.Collections;
34 import java.util.Comparator;
35 public class ListSort {
36      public static void main(String[] args){
37          ArrayList list = new ArrayList();
38          list.add(new Person("lcl",28));
39          list.add(new Person("fx",23));
40          list.add(new Person("wqx",29));
41          Comparator comp = new Mycomparator();
42          Collections.sort(list,comp);  
43          for(int i = 0;i<list.size();i++){
44              Person p = (Person)list.get(i);
45              System.out.println(p.getName());
46          }   
47      }
48 }

看图,关键是定义一个比较器即可。

ArrayList排序 降序排列

原文:http://www.cnblogs.com/hangaozu/p/6350210.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!