作者热门文章
- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
有没有办法使此方法正确通用并消除警告?
/**
* <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
时出错.对于前者,即:
The method compareTo(capture#9-of ?) in the type Comparable is not applicable for the arguments (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
更新
此外,查看您的代码我又看到了另一辆自行车,Google Collections 有一个很好的库,它提供了非常方便的 Ordering处理它的想法。
因此,您的代码如下所示:
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);
关于java - 递归泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8415604/
我是一名优秀的程序员,十分优秀!