有没有办法使此方法适当通用并消除警告?
/**
* <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);
}
});
}
I tried Function<? extends Comparable<?>, T>
and Function<? extends Comparable<? extends Comparable>, T>
但都没有编译,调用时出错compareTo
。对于前者来说是:
Comparable 类型中的方法 CompareTo(capture#9-of ?) 不适用于参数 (capture#10-of ? extends Comparable)
尝试这个:
public static <T, C extends Comparable<? super C>> void sortByValue(List<T> list, final boolean ascending, final Function<C, T> valueFunction) {
Collections.sort(list, new Comparator<T>() {
@Override public int compare(T o1, T o2) {
final C v1 = valueFunction.apply(o1);
final C v2 = valueFunction.apply(o2);
return v1.compareTo(v2) * (ascending ? 1 : -1);
}
});
}
你还需要super
允许为子类型定义比较器。更多解释在这里:http://docs.oracle.com/javase/tutorial/extra/generics/morefun.html http://docs.oracle.com/javase/tutorial/extra/generics/morefun.html
UPDATE
另外,看着你的代码,我看到了另一辆自行车,有一个很好的库 Google Collections,它提供了非常方便的Ordering http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Ordering.html处理它的想法。
所以,你的代码将如下所示:
Ordering<NormalTile> myOrdering = Ordering.natural()
.onResultOf(new Function<Integer,NormalTile>() {
public Integer call(NormalTile t) {
return t.getNumber();
}))
.nullsLast();
...
Collections.sort(list, myOrdering);
//or
newList = myOrdering.sortedCopy(readonlyList);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)