我正在尝试创建一个哈希映射,其中包含自定义类的不同子类的哈希集合的哈希映射值,如下所示:
HashMap<String, Hashmap<String, HashSet<? extends AttackCard>>> superMap
AttackCard
有一些子类,例如:Mage
、Assassin
、Fighter
。超级Map中的每个HashMap将只包含一种AttackCard
。
当我尝试添加一个
HashMap<String, HashSet<Assassin>>
当我将代码移植到SuperMap时,我遇到了编译错误: 以下是出错的代码段:
public class CardPool {
private HashMap<String, HashMap<String, HashSet<? extends AttackCard>>> attackPool =
new HashMap<>();
private ArrayList<AuxiliaryCard> auxiliaryPool;
public CardPool() {
(line 24)this.attackPool.put("assassins", new AssassinPool().get());
/* this.attackPool.put("fighters", new Fighter().getPool());
this.attackPool.put("mages", new Mage().getPool());
this.attackPool.put("marksmen", new Marksman().getPool());
this.attackPool.put("supports", new Support().getPool());
this.attackPool.put("tanks", new Tank().getPool());
*/
this.auxiliaryPool = new ArrayList<>(new AuxiliaryCard().getPool());
}
以下是AssassinPool get方法的代码片段:
private HashMap<String, HashSet<Assassin>> pool = new HashMap<>();
public HashMap<String, HashSet<Assassin>> get() {
return pool;
}
我想评论一下,通过将所有 AttackCardPools 比如 AssassinPool 返回并包含 AttackCard 的 HashSet 而不是它们各自的子类,我可以轻松解决我的问题并得到一个良好运行的程序。不过,现在我正在尝试理解这个编译错误 :)
compilation error at line 24: error: no suitable method found for `put(String, HashMap<String,HashSet<Assassin>>>`
this.attackPool.put("assassins", new AssassinPool(). get());
method HashMap.putp.(String, HashMap<String,HashSet<? extends AttackCard>>>` is not applicable (actual argument `HashMap<String, HashSet<Assassin>>` cannot be converted to `HashMap<String, HashSet<? extends AttackCard>>` by method invocation conversion)