posts - 60,comments - 71,trackbacks - 0

            实现对象排序有两种方式,一种是实现Comparator接口,另一种是实现Comparable接口,两者的不同之处是
    前一种方式要实现的是
    int compare(Object o1,Object o2) {
        return ((User) o1).getAge() - ((User)o2).getAge();
    },这个方法,
   后一种方式是要实现的是
   int compareTo(Object o) {
    return this.age - ((User) o).getAge();
  }
  使用时,前一种方式是:Arrays.sort(users,new te());第一个参数是要排序的对象数组,
  第二个参数是一个要实现Comparator接口的类,如果该对象未实现Comparator接口,则需单独提供一个实现Comparator接口的类;
  后一种方式是:Arrays.sort(users);只需一个对象数组参数即可,该对象必须实现Comparable接口,当使用第二种方式时,还可以
  提供升序变降序(反之亦可)的参数,Collections.reverseOrder();
 
  另外两种方式都可以在要实现的方法中根据某些"标志"来实现对对象的不同属性进行排序,如User对象有年龄,姓名,收入等属性,现在有
  这样一个需求,在页面上显示了此对象的各种属性值,现在要点击年龄时按年龄排序,点击收入时按收入排序(也即常说的点击表头排序),就
  可以采用这种方式,具有体如下:
  static flag = "1";
  int compareTo(Object o) {
  if(flag.equals("1")) {
    return this.age - ((User) o).getAge();
  }
  else if(flag.equals("2")) {
      return this.salar - ((User) o).getSalar();
  }
  else {
      return this.age - ((User) o).getAge();
  }
  ......
  定义一个类变量,在页面上单击进判断,如果单击的是年龄,则在处理的类当中将flag设为1,单击收入时,设为2,这样就可以根据对象的不同
  属性进行排序了.


  下面是源代码:

 1package com.rao.test.compare;
 2
 3/*
 4 * Created on 2008-4-25
 5 * Author henry
 6 * TODO To change the template for this generated file go to
 7 * Window - Preferences - Java - Code Style - Code Templates
 8 */

 9
10import java.util.Arrays;
11
12/**
13 * @author tcl-user
14 *
15 * TODO To change the template for this generated type comment go to
16 * Window - Preferences - Java - Code Style - Code Templates
17 */

18public class UserComparable implements Comparable {
19    private String id;
20    private int age;
21
22    public UserComparable(String id, int age) {
23      this.id = id;
24      this.age = age;
25    }

26
27    public int getAge() {
28      return age;
29    }

30
31    public void setAge(int age) {
32      this.age = age;
33    }

34
35    public String getId() {
36      return id;
37    }

38
39    public void setId(String id) {
40      this.id = id;
41    }

42    
43    public int compareTo(Object o) {
44        return this.getAge() - ((UserComparable)o).getAge();
45    }

46    
47
48
49    /**
50     * 测试方法
51     */

52    public static void main(String[] args) {
53        UserComparable[] users = new UserComparable[] new UserComparable("abc"30), new UserComparable("def"10) };
54      Arrays.sort(users);
55      for (int i = 0; i < users.length; i++{
56          UserComparable user = users[i];
57        System.out.println(user.getId() + " " + user.getAge());
58      }

59    }

60
61  }
posted on 2008-04-26 21:23 henry1451 阅读(795) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: