有没有办法使这种方法正确通用,并取消警告?递归泛型
/**
* <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
错误。对于前者即:(?捕获#10的延伸可比)
方法的compareTo在类型可比(?捕获#9的)不适用于参数
你能还提供了'Function'类? – melihcelik
嗨,我正在看看这个问题,并没有真正到达任何地方。但我的一个意见是,不要否定'compareTo()'的结果,因为如果有人返回'Integer.MIN_VALUE',它将保持为'Integer.MIN_VALUE',并且排序顺序不会是你想要的。相反,当上升为假时,反转该呼叫,例如,从'a.compareTo(b)'到'b.compareTo(a);'。烦我知道... – Grundlefleck
@Grundlefleck谢谢,我实现了。 –