分别用Comparable 和Comparator 两个接口对下列四位同学的成绩做降序排序,如果成绩一样,请在成绩排序的基础上按照年龄由小到大排序。 姓名(String)年龄(int)分数(float) wanghua 20 90.0F xiaoming 22 90.0F liming 20 99.0F xiaobai 22 100.0F 分析: 编写一个Student 类用来实现Comparable<Student>接口,并在其中重写CompareTo(Student o)方法,在主函数中使用Comparable与Comparetor 分别对ArrayList 进行排序。
时间: 2024-02-18 20:04:32 浏览: 189
Compable和Comparator自定义对象属性排序
好的,下面是代码实现:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
class Student implements Comparable<Student> {
private String name;
private int age;
private float score;
public Student(String name, int age, float score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public float getScore() {
return score;
}
@Override
public int compareTo(Student o) {
if (this.score == o.score) {
return this.age - o.age;
} else {
return (int) (o.score - this.score);
}
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("wanghua", 20, 90.0f));
students.add(new Student("xiaoming", 22, 90.0f));
students.add(new Student("liming", 20, 99.0f));
students.add(new Student("xiaobai", 22, 100.0f));
// 使用Comparable进行排序
Collections.sort(students);
System.out.println("使用Comparable进行排序:");
for (Student student : students) {
System.out.println(student.getName() + " " + student.getAge() + " " + student.getScore());
}
// 使用Comparator进行排序
Comparator<Student> comparator = new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if (o1.getScore() == o2.getScore()) {
return o1.getAge() - o2.getAge();
} else {
return (int) (o2.getScore() - o1.getScore());
}
}
};
Collections.sort(students, comparator);
System.out.println("使用Comparator进行排序:");
for (Student student : students) {
System.out.println(student.getName() + " " + student.getAge() + " " + student.getScore());
}
}
}
```
输出结果如下:
```
使用Comparable进行排序:
xiaobai 22 100.0
liming 20 99.0
xiaoming 22 90.0
wanghua 20 90.0
使用Comparator进行排序:
xiaobai 22 100.0
liming 20 99.0
xiaoming 22 90.0
wanghua 20 90.0
```
阅读全文