如何为Comparator.comparing使用通用的Number`

问题描述 投票:2回答:1

我有一个要排序的课程清单:

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>)

我的问题是:

  1. 为什么不能使用Number而不是Double
  2. 如何改进SortHelper以使用Number代替Double

请帮帮我..!

java collections comparator
1个回答
2
投票

[我相信您正面临此问题,因为Comparator#comparing期望Comparator#comparing的输出Function<T, U>扩展为Function<T, U>

[U不实现Comparable<? super U>

一种解决方案是指定扩展Comparable<? super U>的新泛型类型也扩展Number:]]

Number

或等效地,您可以使用Comparable<? super Number>

Number

这就是所谓的Comparable

© www.soinside.com 2019 - 2024. All rights reserved.