实体类和外部比较器类代码如下所示:
package com.test.Test09; import java.util.Comparator; public class Student{ private int age; private double height; private String name; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Student(int age, double height, String name) { this.age = age; this.height = height; this.name = name; } @Override public String toString() { return "Student{" + "age=" + age + ", height=" + height + ", name='" + name + '\'' + '}'; } } class BiJiao01 implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { //return 0; //比较年龄 return o1.getAge()-o2.getAge(); } } class BiJiao02 implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { //比较姓名 return o1.getName().compareTo(o2.getName()); } } class BiJiao03 implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { //在年龄相同的情况下比较身高,年龄不同比较年龄 if(o1.getAge()-o2.getAge() == 0) { return ((Double)(o1.getHeight())).compareTo((Double)(o2.getHeight())); }else{ //年龄不一样 return o1.getAge()-o2.getAge(); } } } 测试类如下所示:
package com.test.Test09; import com.test.Test09.Student; public class Test02 { public static void main(String[] args) { //比较两个学生 Student s1 = new Student(9, 160.2, "alili"); Student s2 = new Student(14, 170.5, "bnana"); /*//获取外部比较器 BiJiao01 bj1 = new BiJiao01(); //1.比较年龄 System.out.println(bj1.compare(s1,s2)); //0 -5*/ /*//获取外部比较器 BiJiao02 bj2 = new BiJiao02(); //2.比较姓名 System.out.println(bj2.compare(s1,s2)); // 2 -1*/ //3.在年龄相同的情况下比较身高,年龄不同比较年龄 BiJiao03 bj3 = new BiJiao03(); System.out.println(bj3.compare(s1,s2));//-5 } }