关于对 java 泛型中T extendscompareable<? super T>理解

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章