【发布时间】:2011-12-07 12:53:54
【问题描述】:
有没有办法使此方法正确通用并消除警告?
/**
* <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类? -
嗨,我正在研究这个问题,但并没有真正得到任何结果。但我的一条评论是,不要否定
compareTo()的结果,因为如果有人返回Integer.MIN_VALUE,它将保持Integer.MIN_VALUE并且排序顺序不会是你想要的。相反,当升序为假时,反转调用,例如从a.compareTo(b)到b.compareTo(a);。我知道很烦人... -
@Grundlefleck 谢谢,我实现了。