ArrayList排序 降序排列

时间:2022-07-22 19:47:07
 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 }

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