有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为泛型类中的通配符传递任何具体类都会产生错误。为什么?

我有一种方法,可以用整型键和任何类型的值对复合条目对象列表进行排序。其签名如下:

static void bucketSort(List<Entry<Integer, ?>> list, int n)
{
    //some code
}

其中录入界面如下:

interface Entry<K, V> {
    K getKey(); //returns key stored in this entry
    V getValue(); //returns the value stored in this entry
}

然而,即使在我的理解中,任何对象都可以被传递为“?”,此代码在第二行生成编译错误(“无法解析方法”):

List<Entry<Integer, String>> list = new ArrayList<>();
bucketSort(list, 100);

此外,此代码没有错误:

List<Entry<Integer, ?>> list = new ArrayList<>();
bucketSort(list, 100);

谁能帮我理解为什么会这样?还有,解决这个问题的建议方法是什么


共 (1) 个答案

  1. # 1 楼答案

    Entry对象使用通配符同样,通配符表示未知类型。在上面的代码中,您使用键Integer和值unknown type定义了Entry<Integer, ?>条目,但您必须以同样的方式表示List中的条目对象

    static void bucketSort(List<? extends Entry<Integer, ?>> list, int n)
    {
        //some code
    }