public static <T extends Comparable<? super T>> void sort(List<T> list)

This declaration says, that argument to sort() method must be of a type List<T>, 
where T could be any type that implements Comparable<? super T> (sort requires compareTo method defined in Comparable to compare elements of list)
Comparable<? super T> means that type ? passed to Comparable could be T or any supertype of T. 

Consider this code: 

class A implements Comparable<A>{

	private int i = 0; 
	A(int x){
		i = x;
	}
	
	@Override
	public int compareTo(A o) {
		return i - o.i;
	}
	
	public String toString(){
		return ""+i;
	}
	
}

class B extends A{
	B(int x){
		super(x + 10);
	}
	//we don't override compareTo
}

public class Test {
	
	public static void main(String[] args){
		List<B> list = new ArrayList<B>();
		list.add(new B(3));
		list.add(new B(1));
		list.add(new B(4));
		list.add(new B(2));
		Collections.sort(list);//public static <T extends Comparable<? super T>> void sort(List<T> list)1
		for(B x : list){
			System.out.println(x);
		}
	}
}
 

 

Class B doesn't implement Comparable<B> (and doesn't define it's own compareTo(B b) method). 
Class B inherits compareTo(A x) method from class B (we can say that it implements Comparamble<A>). 
And sort(List<B>) compiles fine, it is conforming with declaration: public static <B extends Comparable<? super B>> void sort(List<B> list)

回答: 根据提供的引用内容,Listsort()方法是Collections工具类中的一个静态方法,用于对List类型进行排序。sort()方法有两种参数形式。第一种形式是使用Comparable接口进行排序,即public static <T extends Comparable<? super T>> void sort(List<T> list)。第二种形式是使用Comparator接口进行排序,即public static <T> void sort(List<T> list, Comparator<? super T> c)。\[1\]如果我们想要得到一个降序的list,可以自定义一个函数,并在sort()方法中传入该函数名作为参数。\[2\]另外,可以在main函数中调用sort()方法对自定义的数据类型进行排序,例如使用sortEmpByIDafaultMode()方法对empList进行排序。\[3\] #### 引用[.reference_title] - *1* *3* [Java基础:Collections.sort的两种用法详解](https://blog.youkuaiyun.com/weixin_45525272/article/details/125275363)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [C++ STL list.sort( ) 高级用法](https://blog.youkuaiyun.com/m0_46628923/article/details/107271405)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值