无法将通配符比较器传递给函数

Can't pass wildcard Comparator to function

我在 ArrayList 的克隆中有以下 sort 方法:

@SuppressWarnings({"rawtypes", "unchecked"})
public void sort(Comparator<? super E> c){
    if(c == null){
        // Use ascending order (only works if types are comparable)
        class ascComparator<T> implements Comparator<T> {
            public int compare(T a, T b) {
                // This will raise an exception if the types are not comparable
                return ((Comparable)a).compareTo(b);
            }
        }
        c = new ascComparator<E>();
    }
    // Cast the internal array to comparable then call merge sort
    sorter.mergeSort((Comparable[])array, c);
}

sorter 对象是 Sort 的一个实例:

public class Sort {
    @SuppressWarnings("unchecked")
    public <E extends Comparable<E>> E[] mergeSort(E[] list, Comparator<? super E> c){
        ...
    }
}

我在 sorter.mergeSort 行收到以下错误:

The method mergeSort(E[], Comparator<? super E>) in the type Sort is not applicable for the arguments (Comparable[], Comparator<capture#8-of ? super E>)

我不确定为什么会发生这种情况,因为参数和参数的类型都是 Comparator<? super E>

感谢大家的评论。我现在已经修好了。

@SuppressWarnings("unchecked")
public void sort(Comparator<? super E> c){
    if(c == null){
        // Use ascending order (only works if types are comparable)
        class ascComparator<T> implements Comparator<T> {
            public int compare(T a, T b) {
                // This will raise an exception if the types are not comparable
                return ((Comparable<T>)a).compareTo(b);
            }
        }
        c = new ascComparator<E>();
    }
    // Cast the internal array to E then call merge sort
    sorter.sort((E[]) array, c);
}

正如 Kayaman 所说,我不应该使用 rawtypes,所以我给出了 ascComparator 参数 T。我还将 array 转换为 E 而不是 Comparable,因为它没有按照我的想法进行。我也改变了 Sort:

@SuppressWarnings("unchecked")
private <E> E[] mergeSort(E[] list, Comparator<E> c){
    ...
}

正如 Louis Wasserman 所指出的,我不需要 Comparable 类型转换。

问题是由于 <? super E> 中的 ? - 两个不同的 ? 可能是不同的类型,并且是这样处理的。您可以从消息部分“capture#8-of ?”中看到。

此外,您混合使用原始类型和未经检查的类型转换也无助于解决您的问题。在您的代码中,您必须在没有类型参数的情况下转换为 Comparable