使用Arrays对数组进行排序（一）

package comparable.demo;

public class Person {

int age;
String name;

public Person(String name, int age) {
this.age = age;
this.name = name;
}

public String toString() {
return "name:" + name + ",age:" + age;
}

}

package comparable.demo;

import java.util.Comparator;

public class CompparatorA implements Comparator<Object> {

@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Person p1 = (Person) o1;
Person p2 = (Person) o2;
return p1.name.compareTo(p2.name);
}

}

package comparable.demo;

import java.util.Comparator;

public class ComparatorB implements Comparator<Object> {

@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Person p1 = (Person) o1;
Person p2 = (Person) o2;
return p1.age > p2.age ? 1 : p1.age == p2.age ? 0 : -1;
}

}

package comparable.demo;

import java.util.Arrays;

public class ComparatorTest {

public static void main(String[] args) {
Person[] p = new Person[] { new Person("A", 10), new Person("B", 11),
new Person("C", 12), new Person("D", 14), new Person("E", 13), };
System.out.println("按姓名排序");
Arrays.sort(p, new CompparatorA());
for (int i = 0; i < p.length; i++) {
System.out.println(p[i]);
}

//        System.out.println("-------------------");
System.out.println("按年龄排序");

Arrays.sort(p, new ComparatorB());
for (int i = 0; i < p.length; i++) {
System.out.println(p[i]);
}
}

}

04-13 619

08-19 606

11-02 269

01-11 267

07-29 1621

08-18 1342

05-06 4834

07-06 1682

10-15 139

09-19 2008