递归泛型

Bar*_*lom 4 java generics unchecked

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

/**
 * <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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

我试过Function<? extends Comparable<?>, T>Function<? extends Comparable<? extends Comparable>, T>,但没有编制,对调用一个错误compareTo.前者是:

Comparable类型中的compareTo(捕获#9-of?)方法不适用于参数(捕获#10-of?extends Comparable)

kan*_*kan 5

试试这个:

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);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

您还需要super允许为子类型定义的比较器.更多解释:http://docs.oracle.com/javase/tutorial/extra/generics/morefun.html

UPDATE

此外,看看你的代码,我看到另一辆自行车,有一个很好的库,谷歌收藏,提供非常方便的订购概念来处理它.

所以,你的代码看起来像:

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);
Run Code Online (Sandbox Code Playgroud)