题目:对下列的成绩表按总成绩进行降序排序,如果总成绩相同时按Java成绩降序排序。
姓名 | Java成绩 | MySQL成绩 | 总成绩 |
---|---|---|---|
张三 | 100 | 59 | 159 |
李四 | 100 | 100 | 200 |
王五 | 98 | 96 | 194 |
赵六 | 96 | 98 | 194 |
陈七 | 59 | 100 | 159 |
程序代码:
import java.util.ArrayList;
import java.util.Collections;
public class ObjectSort {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("张三",100,59));
list.add(new Student("李四",100,100));
list.add(new Student("王五",98,96));
list.add(new Student("赵六",96,98));
list.add(new Student("陈七",59,100));
Collections.sort(list);
for(int i=0;i<list.size();i++) {
System.out.println(list.get(i));
}
}
}
class Student implements Comparable<Student>{
String student_name;
int java_score;
int mysql_score;
int total_score;
public Student(String student_name,int java_score,int mysql_score) {
this.student_name = student_name;
this.java_score = java_score;
this.mysql_score = mysql_score;
this.total_score = java_score+mysql_score;
}
@Override
public String toString() {
return "Student [student_name=" + student_name + ", java_score=" + java_score + ", mysql_score=" + mysql_score
+ ", total_score=" + total_score + "]";
}
@Override
public int compareTo(Student other) {
if(this.total_score==other.total_score) {
return other.java_score-this.java_score;
} else {
return other.total_score-this.total_score;
}
}
}