好久没用过比较器了,算是练手吧
/**
* 学生对象类
*
* @author Willie
*
*/
class Student {
private String name;// 姓名
private int age;// 年龄
private int height;// 身高
public Student() {
}
public Student(String name, int age, int height) {
this.name = name;
this.age = age;
this.height = height;
}
@Override
public String toString() {
return "姓名:" + name + " 年龄:" + age + " 身高:" + height;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
/**
* Student对象比较器
*
* @author Willie
*/
class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
// 比较两个学生的姓名,在字典顺序中,s1在s2的前面则返回-1,反之亦然
int tmpN = s1.getName().compareTo(s2.getName());
if (tmpN < 0)
return -1;
else if (tmpN > 0)
return 1;
// 当s1和s2的名字一样时,比较他们的年龄
else {
// 若s1的年龄小于s2则返回-1,反之亦然
int tmpA = s1.getAge() - s2.getAge();
if (tmpA < 0)
return -1;
else if (tmpA > 0)
return 1;
// 当s1和s2的姓名、年龄都一样时,比较他们的身高
else {
// 若s1的身高小于s2则返回-1,反之亦然
int tmpH = s1.getHeight() - s2.getHeight();
if (tmpH < 0)
return -1;
else if (tmpH > 0)
return 1;
// 当s1和s2的姓名、年龄和身高都一样时就返回0
return 0;
}
}
}
}
// 测试代码
public static void main(String[] args) {
Student stu0 = new Student("张三", 12, 150);
Student stu1 = new Student("张三", 13, 150);
Student stu2 = new Student("张三", 12, 160);
Student stu3 = new Student("李四", 12, 150);
Student stu5 = new Student("张二", 12, 150);
Student stu6 = new Student("张四", 12, 150);
Student[] stus = new Student[] { stu0, stu1, stu2, stu3, stu5, stu6 };
Arrays.sort(stus, new StudentComparator());
for (Student student : stus) {
System.out.println(student);
}
}
Java之text
最新推荐文章于 2021-07-26 11:26:21 发布