public class People {
class Family extends People {
}
}
public class Together {
private static ConcurrentMap<String, Collection<Family>> familyMap= new ConcurrentHashMap<String, Collection<Family>>();
private static ConcurrentMap<String, ConcurrentMap<String, Collection<People>>> registry2 = new ConcurrentHashMap<String, ConcurrentMap<String, Collection<People>>>();
static {
registry2.put(Family.class.toString(), familyMap);
}
}
(我已尝试将registry2
的声明更改为? extends People
错误是:
The method put(String, ConcurrentMap<String,Collection<People>>) in the type Map<String,ConcurrentMap<String,Collection<People>>> is not applicable for the arguments (String, ConcurrentMap<String,Collection<Family>>)
如何将familyMap
放入registry2
hashmap?
答案 0 :(得分:3)
这不是Map问题:这是一个泛型问题。您假设Collection<Family>
是Collection<People>
的子类,因为Family extends People
,但事实并非如此。
它们实际上是完全不同的类型,因此编译器抱怨您没有传递正确类型的参数。
您可以通过将familyMap设置为包含People对象集合的Map来解决此问题。您的代码恰好将Family对象放入其中,这很好,因为一个家庭就是一个人。
但是当将Family对象从地图中取回时,如果需要使用特定的Family函数,则需要将它们类型化为一个Family,尽管有一些风险,即人们(而不是一个家庭)物体可以潜入它。您可能需要考虑不同的设计范例来降低风险。
答案 1 :(得分:0)
您尝试输入不兼容的类型,因为familyMap
是Collection<Family>
,而不是您在Collection<People>
registry2
中指定的ConcurrentMap<String, Collection<People>>