Java无法在Map ADT接口中实现以Pair类作为其通用参数的函数
问题描述:
我创建了具有通用函数entries()
的地图接口。Java无法在Map ADT接口中实现以Pair类作为其通用参数的函数
// 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
,而不会缩小可能会失败的范围。
+0
非常感谢! – engalsh
请发布您定义的地图界面 –