我有一个继承链,其中父类(super class)有 3 个直接子类:Subclass1、Subclass2、Subclass3。
我有一个:
HashMap<Integer, HashMap<Integer, HashSet<Superclass>>> map = new HashMap<>();
我希望map包含3个hashmaps,分别为整数值1、2和3。这3个hashmaps的每个HashSet值都只包含一个Superclass的子类。
例如map.get(1)应该引用
HashMap<Integer, HashSet<Subclass1>>
但是由于编译器错误,我不允许将上述 HashMap 添加到映射:
(actual argument HashMap<Integer, HashSet<Subclass1>> cannot be converted to
HashMap<String, HashSet<Superclass>> by method invocation conversion)
最佳答案
如果您希望能够在运行时将子类添加到 HashSet 中,那么您可以将变量声明为:
HashMap<Integer, HashMap<Integer, HashSet<? extends Superclass>>> map ...
关于Java HashMap/HashSet 多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19137407/