>我有一个继承链,其中超类有 3 个直接子类,子类 1、子类 2、子类 3。
我有一个:
HashMap<Integer, HashMap<Integer, HashSet<Superclass>>> map = new HashMap<>();
我希望 map 包含 3 个整数值为 1、2 和 3 的哈希映射。这 3 个哈希映射将分别具有仅包含超类的一个子类的 HashSet 值。
例如 map.get(1) 应该引用
HashMap<Integer, HashSet<Subclass1>>
但是由于编译器错误,我不允许将上面的哈希图添加到映射中:
(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 ...
由于我们的 OP 似乎不相信您可以创建对象数组(主要是 ArrayLists),让我们来看看一些基础知识。
ArrayList<String>[] arrayOfArraylists = new ArrayList[10];
arrayOfArraylists[0] = new ArrayList<String>();
了不起。
现在是原始问题。
Map<Integer, Map<Integer,HashSet<? extends SuperClass>>> map = new HashMap<>();
map.put(1, new HashMap<Integer, HashSet<? extends SuperClass>>());
map.get(1).put(2, new HashSet<SubClass>());
我不知道我是否想像这样对地图进行分层,或者我是否愿意将第一张地图仅用于 3 个项目。
您可以创建一个索引类,并且只有一个地图图层。
Map<Triplet, HashSet<? extends SuperClass>> map = new HashMap<>();
map.put(new Triplet(1, 2, 3), new HashSet<SubClass>());