完善并运行如下程序,使其能够按如下规则排序:先按age升序排,当age相同时,再按name升序排。 import java.util.TreeSet; class Teacher implements Comparable { String name; int age; public Teacher(String name, int age) { this.name = name; this.age = age; } public String toString() { return name + ":" + age; } //在此处补充排序依据代码 } public class SortTeacher { public static void main(String[] args) { TreeSet ts = new TreeSet(); ts.add(new Teacher("Jack",19)); ts.add(new Teacher("Rose",18)); ts.add(new Teacher("Tom", 19)); ts.add(new Teacher("Rose",18)); System.out.println(ts); } }
时间: 2024-01-03 13:06:01 浏览: 305
import java.util.TreeSet;
class Teacher implements Comparable<Teacher> {
String name;
int age;
public Teacher(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + ":" + age;
}
@Override
public int compareTo(Teacher o) {
// 按age升序排,若age相同时按name升序排
if (this.age != o.age) {
return this.age - o.age;
} else {
return this.name.compareTo(o.name);
}
}
}
public class SortTeacher {
public static void main(String[] args) {
TreeSet<Teacher> ts = new TreeSet<>();
ts.add(new Teacher("Jack", 19));
ts.add(new Teacher("Rose", 18));
ts.add(new Teacher("Tom", 19));
ts.add(new Teacher("Rose", 18));
System.out.println(ts);
}
}
阅读全文