面试题答案
一键面试import java.util.TreeSet;
class Student implements Comparable<Student> {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Student other) {
if (this.age != other.age) {
return this.age - other.age;
} else {
return this.name.compareTo(other.name);
}
}
}
public class Main {
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<>();
treeSet.add(new Student("Alice", 20));
treeSet.add(new Student("Bob", 18));
treeSet.add(new Student("Alice", 18));
for (Student student : treeSet) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
}
}
实现过程说明
- 实现Comparable接口:为了让
Student
类对象能够在TreeSet
中进行自然排序,Student
类实现了Comparable
接口,并实现了compareTo
方法。 compareTo
方法逻辑:- 首先比较两个
Student
对象的age
属性,如果当前对象的age
小于传入对象的age
,返回一个负整数;如果大于,返回一个正整数;如果相等,则比较name
属性。 - 比较
name
属性时,调用String
类的compareTo
方法,该方法会按照字典序进行比较,同样返回负整数、正整数或0,以表示当前对象的name
在字典序上小于、大于或等于传入对象的name
。
- 首先比较两个
- 使用TreeSet:在
main
方法中,创建了一个TreeSet
对象,并向其中添加Student
对象。由于Student
类实现了Comparable
接口,TreeSet
会自动按照compareTo
方法定义的规则对元素进行排序。最后遍历TreeSet
,输出排序后的结果。
如果使用Comparator
接口,步骤如下:
import java.util.Comparator;
import java.util.TreeSet;
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class StudentComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
if (s1.getAge() != s2.getAge()) {
return s1.getAge() - s2.getAge();
} else {
return s1.getName().compareTo(s2.getName());
}
}
}
public class Main {
public static void main(String[] args) {
TreeSet<Student> treeSet = new TreeSet<>(new StudentComparator());
treeSet.add(new Student("Alice", 20));
treeSet.add(new Student("Bob", 18));
treeSet.add(new Student("Alice", 18));
for (Student student : treeSet) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
}
}
使用Comparator接口说明
- 创建Comparator实现类:创建一个实现
Comparator
接口的类StudentComparator
,在compare
方法中定义比较逻辑,与Comparable
接口中compareTo
方法的逻辑一致。 - 使用TreeSet:在创建
TreeSet
对象时,将StudentComparator
的实例作为参数传入构造函数。这样TreeSet
会使用我们自定义的Comparator
来对Student
对象进行排序。