如何在实现 Map 时强制泛型参数超类类型



我有各种各样的GameObject。我想为它们做基本的集合定义:

//Wrong number of type arguments; required 2. > expected
public interface GameObjectMap<T> extends Map<String, T extends GameObject> {
}

集合将全部按字符串映射(因为数据是从 JSON 加载的)。但是第二个泛型类型参数应该是 GameObject 的任何实例。我不知道如何正确编写上面的代码。

你几乎是对的。只需将extends GameObject移动到第一个泛型定义:

public interface GameObjectMap<T extends GameObject> extends Map<String, T> {
}

限制来自T的第一个声明,例如

public interface GameObjectMap<T extends GameObject> extends Map<String, T> {
}

最新更新