码迷,mamicode.com
首页 > 编程语言 > 详细

ArrayList排序 降序排列

时间:2017-01-25 23:05:11      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:tle   main   util   sts   replace   .net   weight   person   排列   

 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排序 降序排列

标签:tle   main   util   sts   replace   .net   weight   person   排列   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!