import java.util.Arrays; import java.util.Comparator; class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return this.name; } public int getAge() { return this.age; } @Override public String toString() { // TODO Auto-generated method stub return ""+this.name+" "+this.age; } } class Cmp implements Comparator { @Override public int compare(Object arg0, Object arg1) { Person a = (Person) arg0; Person b = (Person) arg1; if (a.getName().compareTo(b.getName()) != 0) return a.getName().compareTo(b.getName()); else { if (a.getAge() < b.getAge()) return -1; else if (a.getAge() > b.getAge()) return 1; else return 0; } } } public class Main { public static void main(String[] args) { Person[] p = new Person[4]; p[0] = new Person("ZZZ",19); p[1] = new Person("AAA", 109); p[2] = new Person("AAA", 19); p[3] = new Person("YYY",100); Arrays.sort(p, new Cmp()); System.out.println(Arrays.toString(p)); } }
当然由于比较器的实现类只用显示实现一个方法,因此,我们可以不用专门写一个类来实现它,当我们需要用到比较器时,可以写个匿名内部类来实现 Comparator
import java.util.Arrays; import java.util.Comparator; class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return this.name; } public int getAge() { return this.age; } @Override public String toString() { return ""+this.name+" "+this.age; } } public class Main { public static void main(String[] args) { Person[] p = new Person[4]; p[0] = new Person("ZZZ",19); p[1] = new Person("AAA", 109); p[2] = new Person("AAA", 19); p[3] = new Person("YYY",100); Arrays.sort(p, new Comparator<Object>() { @Override public int compare(Object arg0, Object arg1) { Person a = (Person) arg0; Person b = (Person) arg1; if (a.getName().compareTo(b.getName()) != 0) return a.getName().compareTo(b.getName()); else { if (a.getAge() < b.getAge()) return -1; else if (a.getAge() > b.getAge()) return 1; else return 0; } } }); System.out.println(Arrays.toString(p)); } }
之前一直用的是 Comparable接口,下午把比较器学了下