java中Collections.sort() 排序函数的用法

 1 用Collections.sort方法对list排序有两种方法
2 第一种是list中的对象实现Comparable接口,如下:
3 /**
4 * 根据order对User排序
5 */
6 public class User implements Comparable<User>{
7 private String name;
8 private Integer order;
9 public String getName() {
10 return name;
11 }
12 public void setName(String name) {
13 this.name = name;
14 }
15 public Integer getOrder() {
16 return order;
17 }
18 public void setOrder(Integer order) {
19 this.order = order;
20 }
21 public int compareTo(User arg0) {
22 return this.getOrder().compareTo(arg0.getOrder());
23 }
24 }
25 测试一下:
26 public class Test{
27
28 public static void main(String[] args) {
29 User user1 = new User();
30 user1.setName("a");
31 user1.setOrder(1);
32 User user2 = new User();
33 user2.setName("b");
34 user2.setOrder(2);
35 List<User> list = new ArrayList<User>();
36 //此处add user2再add user1
37 list.add(user2);
38 list.add(user1);
39 Collections.sort(list);
40 for(User u : list){
41 System.out.println(u.getName());
42 }
43 }
44 }
45 输出结果如下
46 a
47 b
48 第二种方法是根据Collections.sort重载方法来实现,例如:
49 /**
50 * 根据order对User排序
51 */
52 public class User { //此处无需实现Comparable接口
53 private String name;
54 private Integer order;
55 public String getName() {
56 return name;
57 }
58 public void setName(String name) {
59 this.name = name;
60 }
61 public Integer getOrder() {
62 return order;
63 }
64 public void setOrder(Integer order) {
65 this.order = order;
66 }
67 }
68
69 主类中这样写即可:
70 public class Test{
71 public static void main(String[] args) {
72 User user1 = new User();
73 user1.setName("a");
74 user1.setOrder(1);
75 User user2 = new User();
76 user2.setName("b");
77 user2.setOrder(2);
78 List<User> list = new ArrayList<User>();
79 list.add(user2);
80 list.add(user1);
81
82 Collections.sort(list,new Comparator<User>(){
83 public int compare(User arg0, User arg1) {
84 return arg0.getOrder().compareTo(arg1.getOrder());
85 }
86 });
87 for(User u : list){
88 System.out.println(u.getName());
89 }
90 }
91 }
92 输出结果如下
93 a
94 b
95 前者代码结构简单,但是只能根据固定的属性排序,后者灵活,可以临时指定排序项,但是代码不够简洁
96
97 择优用之。
posted @ 2012-02-24 14:41  疯子FK  阅读(904)  评论(0编辑  收藏  举报