编程语言
首页 > 编程语言> > java – 递归泛型

java – 递归泛型

作者:互联网

有没有办法使这个方法适当通用并取消警告?

/**
 * <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);
        }
    });
}

我试过功能<?扩展Comparable<?>,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 <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

UPDATE

此外,看看你的代码,我看到另一辆自行车,有一个很好的库,谷歌收藏,提供非常方便的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,generics,unchecked
来源: https://codeday.me/bug/20190610/1208985.html