Java 无法在以 Pair class 作为通用参数的 Map ADT 接口中实现函数
Java Cannot implement a function in Map ADT interface that takes Pair class as its generic parameter
我创建了一个具有通用函数 entries()
的地图界面。
// return iterable collection of all the key-value entries in the map
public ArrayList<Pair<KeyType, ValueType>> entries();
问题是,当我尝试实现接口时,我在接口文件中的 entries()
函数处收到此错误:Bound mismatch: The type KeyType is not a valid substitute for the bounded parameter <KeyType extends Comparable<KeyType>> of the type Pair<KeyType,ValueType>
我实现的功能如下图:
public ArrayList<Pair<KeyType, ValueType>> entries(){
ArrayList<Pair<KeyType, ValueType>> list = new ArrayList<Pair<KeyType, ValueType>>();
preorderList (root, list);
return list;
}
我该如何解决这个问题?
您可能在接口声明中遗漏了一个泛型绑定。由于您的 Pair
要求键可以相互比较 (KeyType extends Comparable<KeyType>
),因此您的 Map
需要在其 KeyType
声明中重申此绑定才能使用 Pair
及其 KeyType
。如果 Pair
限制了它,您可能还需要限制 ValueType
。
interface Map <KeyType extends Comparable<KeyType>, ValueType> { ... }
在通用类型擦除下,Pair
的 KeyType
被替换为 Comparable
。如果您不绑定 Map
的 KeyType
,它将被替换为 Object
,如果没有可能会失败的缩小转换,则无法分配给 Comparable
。
我创建了一个具有通用函数 entries()
的地图界面。
// return iterable collection of all the key-value entries in the map
public ArrayList<Pair<KeyType, ValueType>> entries();
问题是,当我尝试实现接口时,我在接口文件中的 entries()
函数处收到此错误:Bound mismatch: The type KeyType is not a valid substitute for the bounded parameter <KeyType extends Comparable<KeyType>> of the type Pair<KeyType,ValueType>
我实现的功能如下图:
public ArrayList<Pair<KeyType, ValueType>> entries(){
ArrayList<Pair<KeyType, ValueType>> list = new ArrayList<Pair<KeyType, ValueType>>();
preorderList (root, list);
return list;
}
我该如何解决这个问题?
您可能在接口声明中遗漏了一个泛型绑定。由于您的 Pair
要求键可以相互比较 (KeyType extends Comparable<KeyType>
),因此您的 Map
需要在其 KeyType
声明中重申此绑定才能使用 Pair
及其 KeyType
。如果 Pair
限制了它,您可能还需要限制 ValueType
。
interface Map <KeyType extends Comparable<KeyType>, ValueType> { ... }
在通用类型擦除下,Pair
的 KeyType
被替换为 Comparable
。如果您不绑定 Map
的 KeyType
,它将被替换为 Object
,如果没有可能会失败的缩小转换,则无法分配给 Comparable
。