在比较器中,无法将(T, T)应用于(T, T)的比较。

3

Intellij idea给我报错:"Comparator中的compare(T,T)不能应用于(T,T)",代码如下:

public class LCCS<T extends Comparable<T>> {

    private Comparator<T> comparator;

    public LCCS(Comparator<T> comparator) {
        this.comparator = comparator;
    }


    /**
     * Loops the two given lists for finding the longest subequence
     *
     * @param list1 first list.
     * @param list2 second list.
     * @param <T>   list item type.
     * @return LCCS and the sublist indices of the subsequence in list1 and list2.
     */
    private <T> Subsequence<T> getLongestSubsequence(List<T> list1, List<T> list2) {
        Subsequence<T> output = null;
        for (int indexList1 = 0; indexList1 < list1.size(); indexList1++)
            for (int indexList2 = 0; indexList2 < list2.size(); indexList2++)
                if (comparator.compare((T)list1.get(indexList1), (T)list2.get(indexList2)) //Here comes the error
        output = inspectsubsequence(list1, list2, indexList1, indexList2, output);
        return output;
    }
}

我已经将参数类型更改为T,但仍显示相同的消息,只是捕获变成了T。非常感谢您的帮助。


这只是类的一部分哈哈。 - Cees Mandjes
2个回答

4
你在类级别和getLongestSubsequence方法中都有两个不同的泛型类型参数T。尽管它们具有相同的名称,但它们并不相关。因此,comparator.compare不接受与传递给getLongestSubsequence方法的列表元素类型相同的参数类型。
当前的类可以创建一个LCCS<String>实例,然后使用两个List<Integer>参数调用getLongestSubsequence方法。此时,comparator.compare()将期望两个String,而您的代码将向其传递两个Integer。这就是为什么您的代码无法通过编译的原因。
只需从getLongestSubsequence的声明中删除<T>即可,这将导致它使用类级别的T

为什么我需要扩展 <T extends Comparable<T>>?这个扩展真的必要吗? - Cees Mandjes
@CeesMandjes 或许你不需要它。我没有看到你的完整代码,所以无法确定。使用“extends Comparable<T>”类型限定允许你在类内部调用T实例上的“compareTo(T)”方法。例如,如果“comparator”为空,你可以调用“list1.get(indexList1).compareTo(list2.get(indexList2))”,而不是“comparator.compare(list1.get(indexList1), list2.get(indexList2))”。 - Eran

4
类级别,类型参数T在此处被定义:
public class LCCS<T extends Comparable<T>> {

接下来,这段代码为方法的作用域定义了另一个名为T的类型参数;它遮蔽了类级别的声明:

private <T> Subsequence<T> getLongestSubsequence(...

修改这段代码。让方法 resuse 重复使用类级别的类型参数 T

private Subsequence<T> getLongestSubsequence(...

为什么我需要扩展 <T extends Comparable<T>>?这个扩展真的必要吗? - Cees Mandjes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接