题目:同上篇题目一样,不过这次用外比较器来实现:
代码:
import java.util.Arrays;
import java.util.Comparator;
public class Test {
public static void main(String[] args) {
test1();
}
private static void test1() {
Pupil [] pupils = new Pupil[5];
pupils[0] = new Pupil("一", 16, 200);
pupils[1] = new Pupil("二", 16, 180);
pupils[2] = new Pupil("三", 14, 210);
pupils[3] = new Pupil("四", 18, 222);
pupils[4] = new Pupil("五", 19, 200);
MyComparator my =new MyComparator();
//对数组进行排序
Arrays.sort(pupils,my);
//输出排序后的学生数组
System.out.println(Arrays.toString(pupils));
}
}
class Pupil{
String name;
int age;
int height;
public Pupil() {
super();
// TODO Auto-generated constructor stub
}
public Pupil(String name, int age, int height) {
super();
this.name = name;
this.age = age;
this.height = height;
}
@Override
public String toString() {
return "Pupil [name=" + name + ", age=" + age + ", height=" + height + "]";
}
}
//定义外比较器
class MyComparator implements Comparator<Pupil>{
@Override
public int compare(Pupil o1, Pupil o2) {
if(o1.age>o2.age) {
return 1;
}else if(o1.age<o2.age) {
return -1;
}else if(o1.age==o2.age) {
return o1.height-o2.height;
}
return 0;
}
}