日期:2014-05-20 浏览次数:20745 次
public class SortTest { public static void main(String[] args) { Student s1 = new Student("Zhang", 80); Student s2 = new Student("Zhang", 68); Student s3 = new Student("Zhang", 71); Student s4 = new Student("Li", 80); Student[] ss = { s1, s2, s3, s4 }; // 以上是测试的数组 for (Student s : ss) System.out.println(s); // 这个就是排序了 Arrays.sort(ss); System.out.println("============="); for (Student s : ss) System.out.println(s); } } /** * * 类Student实现 Comparable接口,以方便排序 * * */ class Student implements Comparable<Student> { public String name; public int point; public Student() { } public Student(String name, int point) { this.name = name; this.point = point; } /** * * 实现Comparable<Student>接口的方法 * */ public int compareTo(Student o) { int stringCompare = this.name.compareTo(o.name); if (stringCompare == 0) { // 如果名字比较相同,返回的是成绩的比较结果 return this.point - o.point; } else { // 如果名字比较不同,直接返回比较结果 return stringCompare; } } /* * 方便打印 */ public String toString() { return this.name + "\t" + point; } }