创建了一个学生类,同时在实现Comparable接口后,重写了其中的compareto方法,使总成绩可以由高到低排序
package com.edu.homework; public class Student implements Comparable<Student>{//使用自然排序实现comparable接口并重写其中额比较方法 private String name; private int chinese; private int math; private int english; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getChinese() { return chinese; } public void setChinese(int chinese) { this.chinese = chinese; } public int getMath() { return math; } public void setMath(int math) { this.math = math; } public int getEnglish() { return english; } public void setEnglish(int english) { this.english = english; } public Student(String name, int chinese, int math, int english) { super(); this.name = name; this.chinese = chinese; this.math = math; this.english = english; } public Student() { super(); // TODO Auto-generated constructor stub } public int getAllscores(){ return chinese+math+english; } //从重写compareto方法 @Override public int compareTo(Student s) { int num = s.getAllscores()-this.getAllscores();//总成绩由大到小排序 int num2 = num==0?this.name.compareTo(s.name):num;//如果总成绩一样,那么再按照名字自然排序 return num2; } }