ArrayList的排序
[代码] [Java]代码
01 | import java.util.ArrayList; |
02 | import java.util.Collections; |
03 | import java.util.Comparator; |
04 |
05 | public class ArrayListSort { |
06 |
07 | public static void main(String[] args) { |
08 | ArrayList<Person> persons = new ArrayList<Person>(); |
09 | Person zhangsan = new Person( "zhangsan" , 20 , true ); |
10 | Person lisi = new Person( "lisi" , 21 , true ); |
11 | Person wangwu = new Person( "wangwu" , 18 , false ); |
12 | persons.add(zhangsan); |
13 | persons.add(lisi); |
14 | persons.add(wangwu); |
15 |
16 | Collections.sort(persons, new Comparator<Person>() { |
17 | @Override |
18 | public int compare(Person o1, Person o2) { |
19 | if (o1 != null && o2 != null ) { |
20 | if (o1.getAge() > o2.getAge()) { |
21 | return 1 ; |
22 | } else if (o1.getAge() < o2.getAge()) { |
23 | return - 1 ; |
24 | } |
25 | } |
26 | return 0 ; |
27 | } |
28 | }); |
29 |
30 | for (Person p : persons) { |
31 | System.out.println(p); |
32 | } |
33 | } |
34 |
35 | } |
36 | class Person { |
37 |
38 | private String name; |
39 | private int age; |
40 | private boolean sex; |
41 |
42 | public Person() { |
43 | } |
44 |
45 | public Person(String name, int age, boolean sex) { |
46 | this .name = name; |
47 | this .age = age; |
48 | this .sex = sex; |
49 | } |
50 |
51 | public String getName() { |
52 | return name; |
53 | } |
54 |
55 | public void setName(String name) { |
56 | this .name = name; |
57 | } |
58 |
59 | public int getAge() { |
60 | return age; |
61 | } |
62 |
63 | public void setAge( int age) { |
64 | this .age = age; |
65 | } |
66 |
67 | public boolean isSex() { |
68 | return sex; |
69 | } |
70 |
71 | public void setSex( boolean sex) { |
72 | this .sex = sex; |
73 | } |
74 |
75 | @Override |
76 | public String toString() { |
77 | return "name=" + name + "\tage=" + age + "\tsex" + sex; |
78 | } |
79 |
80 | } |