# 使用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]);
}
}

}

• 本文已收录于以下专栏：

举报原因： 您举报文章：使用Arrays对数组进行排序（一） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)