小实例-实现对成绩总分由高到低的排序-Java中数组对象的排序

这个SortTotalScore类的功能是:对于一组由学生班级,姓名,各科成绩组成的记录列表,统计出每个学生的总分,并且按照总分由高到低的顺序显示出学生所有信息。

思路:建立一个由Student类数据组成的一维数组。要对该数组对象的元素进行排序,利用了Arrays类的sort()方法.由于是对象数组,所以Student类必须实现Comparable接口,并且重写compareTO()方法,否则会抛出异常。

//如何实现这对象数组排序 import java.util.Arrays; public class SortTotalScore { public static void main(String args[]) { Student[] st = new Student[10]; st[0] = new Student ("三年二班", "老大",93,84,54,45,89,66,75); st[1] = new Student ("三年二班", "老二",88,65,48,98,56,44,85); st[2] = new Student ("三年二班", "老三",68,74,59,39,64,77,85); st[3] = new Student ("三年二班", "老四",77,85,49,62,18,46,89); st[4] = new Student ("三年二班", "老五",45,39,56,54,66,39,76); st[5] = new Student ("三年二班", "老六",45,87,35,49,85,41,28); st[6] = new Student ("三年二班", "老七",77,87,41,54,64,48,52); st[7] = new Student ("三年二班", "老八",54,75,41,35,54,87,69); st[8] = new Student ("三年二班", "老九",78,98,74,54,12,68,48); st[9] = new Student ("三年二班", "老十",39,22,65,48,88,98,92); Arrays.sort(st); for (int i = 0; i < st.length; i++) { System.out.println(st[i]); } } } class Student implements Comparable { String banji; String mingzi; int yuwen; int shuxue; int yingwen; int lishi; int zhengzhi; int huaxue; int wuli; Student(String banji,String mingzi,int yuwen,int shuxue, int yingwen,int lishi,int zhengzhi,int huaxue,int wuli) { this.banji = banji; this.mingzi = mingzi; this.yuwen = yuwen; this.shuxue = shuxue; this.yingwen = yingwen; this.lishi = lishi; this.zhengzhi = zhengzhi; this.huaxue = huaxue; this.wuli = wuli; } public int getTotalScore() { return yuwen+shuxue+yingwen+lishi+zhengzhi+huaxue+wuli; } public int compareTo(Object o) { Student s=(Student)o; return getTotalScore()

你可能感兴趣的:(J2SE)