2015-04-25 13 views
0

我创建了具有通用函数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; 
} 

我该如何解决这个问题?

+0

请发布您定义的地图界面 –

回答

0

您可能在接口声明中留下了一个通用绑定。由于您的Pair要求密钥相互可比(KeyType extends Comparable<KeyType>),因此您的Map需要在其KeyType声明中重申该限制,以便使用Pair及其KeyType。如果Pair限制它,您可能还需要绑定ValueType

interface Map <KeyType extends Comparable<KeyType>, ValueType> { ... } 

在通用类型擦除,PairKeyType被替换为Comparable。如果您未绑定MapKeyType,则会将其替换为Object,该值不可分配给Comparable,而不会缩小可能会失败的范围。

+0

非常感谢! – engalsh