Java - 使用 Collections.sort() 排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11506525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - sorting using Collections.sort()
提问by user1189571
I have to write a method to sort both Integers and Doubles.
我必须编写一种方法来对整数和双精度进行排序。
public ArrayList<Number> sortDescending(ArrayList<Number> al){
Comparator<Number> c=Collections.reverseOrder();
Collections.sort(al,c);
return al;
}
public ArrayList<Number> sortAscending(ArrayList<Number> al){
Collections.sort(al);
return al;
}
The problem is that in sortAscending, the following error occurs:
问题是在sortAscending中,出现如下错误:
Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (ArrayList). The inferred type Number is not a valid substitute for the bounded parameter < T extends Comparable < ? super T>>
绑定不匹配:Collections 类型的泛型方法 sort(List) 不适用于参数 (ArrayList)。推断类型 Number 不是有界参数的有效替代品 < T extends Comparable < ? 超级T>>
回答by Bohemian
You need to use a generic upper boundof Number
intersecting with Comparable<T>
:
您需要使用与相交的通用上限:Number
Comparable<T>
public <T extends Number & Comparable<T>> ArrayList<T> sortDescending(ArrayList<T> al){
Comparator<T> c=Collections.reverseOrder();
Collections.sort(al,c);
return al;
}
public <T extends Number & Comparable<T>> ArrayList<T> sortAscending(ArrayList<T> al){
Collections.sort(al);
return al;
}
All JDK Numbers
(eg Float
, Integer
etc) match this typing.
所有 JDK Numbers
(例如Float
,Integer
等)都匹配这种类型。
For the uninitiated, the syntax <T extends A & B>
is the way you bound T
to bothA
and B
.
对于新手来说,语法<T extends A & B>
是你绑定的方式T
,以双方A
和B
。
FYI, there is no syntax for "or" logic (nor would it make sense if you think about it)
仅供参考,“或”逻辑没有语法(如果您考虑一下也没有意义)
回答by Oskar Kjellin
You are getting the error because number does not implement Comparable<Number>
. You need to add a generic contstraint so that it extends both number and Comparable. In this case:
您收到错误是因为 number 没有实现Comparable<Number>
。您需要添加一个通用约束,以便它扩展 number 和 Comparable。在这种情况下:
public <T extends Number & Comparable<T>> ArrayList<T> sortAscending(ArrayList<T> al){
Collections.sort(al);
return al;
}