實現對象排序有兩種方式,一種是實現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,這樣就可以根據對象的不同
屬性進行排序了.
下面是源代碼:
1
package 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
10
import 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
*/
18
public 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 閱讀(815)
評論(0) 編輯 收藏