面试题答案
一键面试以下是使用Java实现上述功能的代码:
import java.util.Comparator;
import java.util.TreeSet;
class Student {
String name;
int age;
float score;
public Student(String name, int age, float score) {
this.name = name;
this.age = age;
this.score = score;
}
}
public class Main {
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if (s1.age != s2.age) {
return s1.age - s2.age;
} else if (s1.score != s2.score) {
return Float.compare(s2.score, s1.score);
} else {
return s1.name.compareTo(s2.name);
}
}
});
Student student1 = new Student("Alice", 20, 85.5f);
Student student2 = new Student("Bob", 20, 80.0f);
Student student3 = new Student("Charlie", 19, 90.0f);
treeSet.add(student1);
treeSet.add(student2);
treeSet.add(student3);
for (Student student : treeSet) {
System.out.println("Name: " + student.name + ", Age: " + student.age + ", Score: " + student.score);
}
}
}
- 首先定义了
Student
类,包含name
、age
和score
属性。 - 在
main
方法中创建了TreeSet
,并传入一个自定义的Comparator
。 Comparator
的compare
方法实现了按题目要求的排序逻辑:- 先比较
age
,年龄小的在前。 age
相同则比较score
,分数高的在前。score
也相同则按name
的字典序排序。
- 先比较
- 最后向
TreeSet
中添加学生对象并遍历输出。