關於對 java 泛型中T extendscompareable
阿新 • • 發佈:2019-01-28
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(intid) { 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完整程式碼的實現可參考本文的末尾
以上是別人的摘自:
下面是我的理解
163354117