关于对 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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值