做一个Student类,有sno、sname、score3个属性;实现Comparable接口,按照score降序排序;在测试类的main方法中创建3个Studeng对象放入一个TreeSet,然后遍历看输出
时间: 2024-04-30 17:24:58 浏览: 79
好的,以下是实现代码:
```java
import java.util.*;
class Student implements Comparable<Student> {
private int sno;
private String sname;
private int score;
public Student(int sno, String sname, int score) {
this.sno = sno;
this.sname = sname;
this.score = score;
}
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(Student o) {
return o.score - this.score;
}
@Override
public String toString() {
return "Student{" +
"sno=" + sno +
", sname='" + sname + '\'' +
", score=" + score +
'}';
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(1, "张三", 80);
Student s2 = new Student(2, "李四", 90);
Student s3 = new Student(3, "王五", 85);
Set<Student> set = new TreeSet<>();
set.add(s1);
set.add(s2);
set.add(s3);
for (Student s : set) {
System.out.println(s);
}
}
}
```
运行结果:
```
Student{sno=2, sname='李四', score=90}
Student{sno=3, sname='王五', score=85}
Student{sno=1, sname='张三', score=80}
```
阅读全文