有没有一种方法可以使这个方法真正通用,并消除警告?
/**
* <p>Sort a collection by a certain "value" in its entries. This value is retrieved using
* the given <code>valueFunction</code> which takes an entry as argument and returns
* its value.</p>
*
* <p>Example:</p>
* <pre>// sort tiles by number
*Collects.sortByValue(tileList, true, new Function<Integer,NormalTile>() {
* public Integer call(NormalTile t) {
* return t.getNumber();
* }
*});</pre>
*
* @param list The collection.
* @param ascending Whether to sort ascending (<code>true</code>) or descending (<code>false</code>).
* @param valueFunction The function that retrieves the value of an entry.
*/
public static <T> void sortByValue(List<T> list, final boolean ascending, @SuppressWarnings("rawtypes") final Function<? extends Comparable, T> valueFunction) {
Collections.sort(list, new Comparator<T>() {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override public int compare(T o1, T o2) {
final Comparable v1 = valueFunction.call(o1);
final Comparable v2 = valueFunction.call(o2);
return v1.compareTo(v2) * (ascending ? 1 : -1);
}
});
}
我尝试使用Function<? extends Comparable<?>, T>
和 Function<? extends Comparable<? extends Comparable>, T>
,但是都无法编译通过,因为调用 compareTo
方法时出错。对于前者错误信息如下:
在类型 Comparable 中,方法 compareTo(capture#9-of ?) 对参数 (capture#10-of ? extends Comparable) 不适用
Function
类吗? - melihcelikcompareTo()
的结果,因为如果有人返回Integer.MIN_VALUE
,它将保持为Integer.MIN_VALUE
,排序顺序将不会是您想要的。相反,当升序为false时,反转调用,例如从a.compareTo(b)
到b.compareTo(a);
。很烦人,我知道... - Grundlefleck