Part V
Comparable与Comparator的作用很类似,那到底应该有哪个呢?
这个问题留给读者去思考,在这里我没有这个资格做出评论,只是我在很多的讨论中都了解到用Comparator接口的人比较多。
最后是东方标准杨帆老师使用Comparator的一点心得,谢谢杨老师的教导:
1: import java.util.Comparator;
2:
3: public class Person {
4:
5: private String name;
6: private int age;
7:
8: public Person() {
9: }
10:
11: public Person(String name, int age) {
12: this.name = name;
13: this.age = age;
14: }
15:
16: public String getName() {
17: return name;
18: }
19:
20: public void setName(String name) {
21: this.name = name;
22: }
23:
24: public int getAge() {
25: return age;
26: }
27:
28: public void setAge(int age) {
29: this.age = age;
30: }
31:
32: @Override
33: public String toString() {
34: return "Person [age=" + age + ", name=" + name + "]";
35: }
36:
37: public static final Comparator<Person> PERSON_COMPARATOR = new Comparator<Person>() {
38:
39: @Override
40: public int compare(Person p1, Person p2) {
41: if (p1.getAge() > p2.getAge()) {
42: return 1;
43: } else if (p1.getAge() < p2.getAge()) {
44: return -1;
45: }
46: return 0;
47: }
48: };
49:
50: }
这里定义了一个PERSON_COMPARATOR的静态内部类。
使用方法如下:
1: import java.util.Arrays;
2:
3: public class CompareTest {
4:
5: public static void main(String[] args) {
6: Person[] persons = {
7: new Person("P1", 60),
8: new Person("P2", 20),
9: new Person("P3", 40)
10: };
11:
12: System.out.println(Arrays.toString(persons));
13:
14: Arrays.sort(persons, Person.PERSON_COMPARATOR);
15:
16: System.out.println(Arrays.toString(persons));
17: }
18:
19: }
为什么要这样定义了,因为从上述的例子就可以看出,我们只是调用了这个静态内部类作为方法的参数,而这个静态内部类只会在类加载的时候被实例化一次,换句话说在同一个运行环境中只存在一个这样的实例对象,而像Part IV的写法会产生很多的对象实例。