如何将 Hashmap 转换为 Map

How to cast a Hashmap to Map

我想投射哈希图:

我的代码:

public class Example {

private HashMap<MyItem, Integer> items =new HashMap<MyItem, Integer>();


@Override
public Map<Item, Integer> gItems() {
    return this.items;
}

}

MyItem 是继承自 Item class 的 class。

这段代码给我一个编译错误。

出于多种原因,我无法使用该解决方案来更改 return 方法的类型。

那么我如何将我的 HashMap<MyItem, Integer> 投射到 Map<Item, Integer>

我得到的错误是: 输入 mismatch:cannot 从 HashMap<MyItem, Integer> 转换为 Map<Item, Integer>

并且编译器要求我更改 return 方法的类型。

谢谢。

编辑:参见 testinfected 的回答,right/makes 更有意义。

如果调用您的代码无法处理实现所需接口的类型,则您的堆栈中可能存在问题,但您可以像这样转换:

return (Map)this.items;

您将无法施法,因为 Map<MyItem, Integer> 不是 Map<Item, Integer> 的子类型。这在 generics tutorial 中有详细描述(请参阅泛型和子类型部分)。

在这种情况下你可以做的是让你的函数 return a Map<? extends Item, Integer>