我有一个要排序的课程清单:
class Student {
private Integer studentId;
private Double scoreA;
private Integer scoreB;
private Long scoreC;
// ... getter/setter...
}
而且我想创建一个可用于对Student
列表进行排序的辅助类(带有静态方法):
public class SortHelper {
public static <T> void Sort(List<T> list, Function<T, Double> fn) { // Double
Collections.sort(list, Comparator.comparing(fn));
}
}
但是,上述方法仅需要Double
-但我想将所有Number
对象传递给该方法:
public static <T> void Sort(List<T> list, Function<T, Number> fn) { // `Number`
Collections.sort(list, Comparator.comparing(fn)); // Error!
}
// so that I can do:
List<Student> students = loadStudents();
SortHelper.Sort(students, Student::getScoreA); // Double
SortHelper.Sort(students, Student::getScoreB); // Integer
SortHelper.Sort(students, Student::getScoreC); // Long
[当我使用Number
而不是Double
时,出现错误The method comparing(Function<? super T,? extends U>) in the type Comparator is not applicable for the arguments (Function<T,Number>)
我的问题是:
Number
而不是Double
?SortHelper
以使用Number
代替Double
?请帮帮我..!
[我相信您正面临此问题,因为Comparator#comparing
期望Comparator#comparing
的输出Function<T, U>
扩展为Function<T, U>
。
[U
不实现Comparable<? super U>
。
一种解决方案是指定扩展Comparable<? super U>
的新泛型类型和也扩展Number
:]]
Number
或等效地,您可以使用
Comparable<? super Number>
:
Number
这就是所谓的
Comparable
。