public class Student implements Comparable<Student>{ private int id; public Student(int id) { this.id = id; } @Override public int compareTo(Student o) { return (id > o.id) ? 1 : ((id < o.id) ? -1 : 0); } }
public class CollegeStudent extends Student{ public CollegeStudent(int id) { super(id); } }
先需要根據他們的id對他們進行排序(注意此處是對數組對象進行排序),設計方法如下,(n指數組元素的個數):
public static <T extends Comparable<? super T>> void selectionSort(T[] a,int n)
先理解此方法含義,首先<T extends Comparable<T>>規定了數組中對象必須實現Comparable接口,Comparable<? Super T>表示如果父類實現Comparable接口,其自身可不實現,如CollegeStudent。先假設有一個CollegeStudent的數組,如下:
CollegeStudent[] stu = new CollegeStudent[]{ new CollegeStudent(3),new CollegeStudent(2), new CollegeStudent(5),new CollegeStudent(4)};
執行方法 selectionSort(stu,4)是完全可以通過的。可如果定義的selectionSort方法如下:
public static <T extends Comparable<T>> void selectionSort(T[] a,int n)
則方法selectionSort(stu,4)不能執行,因爲CollegeStudent沒有實現Comparable<CollegeStudent>接口。換句話就是“? super T”使selectionSort方法變得更爲通用了。selectionSort完整代碼的實現可參考本文的末尾
以上是別人的摘自:http://www.linuxidc.com/Linux/2013-10/90928.htm
下面是我的理解
163354117