有没有办法使这个方法适当通用并取消警告?
/**
*
Sort a collection by a certain "value" in its entries. This value is retrieved using
* the given valueFunction
which takes an entry as argument and returns
* its value.
*
*
Example:
*
// sort tiles by number
*Collects.sortByValue(tileList, true, new Function() {
* public Integer call(NormalTile t) {
* return t.getNumber();
* }
*});
*
* @param list The collection.
* @param ascending Whether to sort ascending (true
) or descending (false
).
* @param valueFunction The function that retrieves the value of an entry.
*/
public static void sortByValue(List list, final boolean ascending, @SuppressWarnings("rawtypes") final Function extends Comparable, T> valueFunction) {
Collections.sort(list, new Comparator() {
@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);
}
});
}
我试过功能,T>和功能,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 > void sortByValue(List list, final boolean ascending, final Function valueFunction) {
Collections.sort(list, new Comparator() {
@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);
}
});
}
UPDATE
此外,看看你的代码,我看到另一辆自行车,有一个很好的库,谷歌收藏,提供非常方便的Ordering概念来处理它.
所以,你的代码看起来像:
Ordering myOrdering = Ordering.natural()
.onResultOf(new Function() {
public Integer call(NormalTile t) {
return t.getNumber();
}))
.nullsLast();
...
Collections.sort(list, myOrdering);
//or
newList = myOrdering.sortedCopy(readonlyList);
标签:java,generics,unchecked
来源: https://codeday.me/bug/20190610/1208985.html