这个是我当时做得代码- /*
- * 10、声明类Student,包含3个成员变量:name、age、score,创建5个对象装入TreeSet,按照成绩排序输出结果(考虑成绩相同的问题)
- */
- package com.itheima;
- import java.util.*;
- public class Test10 {
- public static void main(String[] args){
- TreeSet ts=new TreeSet();
- ts.add(new Student("张三",23,90));
- ts.add(new Student("李四",23,80));
- ts.add(new Student("王五",22,80));
- ts.add(new Student("赵六",22,80));
- ts.add(new Student("钱七",22,80));
- System.out.println(ts);
- }
- }
- /*
- * 学生类
- */
- class Student implements Comparable{
- private String name;
- private int age;
- private double score;
-
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- public double getscore(){
- return score;
- }
-
-
- Student(String name,int age,double score){
- this.name=name;
- this.age=age;
- this.score=score;
- }
- @Override
- public int compareTo(Object obj) {
- if (!(obj instanceof Student))
- throw new RuntimeException("不是学生类型");
- Student s = (Student) obj;
- // 按成绩排序,成绩一样按名字
- if (this.score >s.score)return -1;
- else if(this.score<s.score)return 1;
- else if(this.name.compareTo(s.name)>0) return 1;
- else if(this.name.compareTo(s.name)<0)return -1;
- return 0;
-
- }
- public String toString(){
- return "姓名:"+this.name+"成绩:"+this.score+"年龄:"+this.age;
- }
- }
-
-
复制代码
|