public class People {
class Family extends People {
}
}
public class Together {
private static Collection<Family> familyList = new ArrayList<Family>();
private static ConcurrentMap<String, Collection<People>> registry = new ConcurrentHashMap<String, Collection<People>>();
static {
registry.put(Family.class.toString(), familyList);
}
}
错误信息:
The method put(String, Collection<people>) in the type Map<String,Collection<people>> is not applicable for the arguments (String, Collection<family>)
为什么我不能输入 familyList
进入registry
?我认为自 family
延伸people
我应该能够将子类型放入父类(super class)型中 registry
.
编辑:以上问题已解决。我的问题的最后一部分涉及一个使用相同名称的更复杂的示例:
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>>)
最佳答案
因为 Collection<family>
不是 Collection<people>
.换句话说:Java collections are not covariant.
Is there a way I could put family into the hashmap?
将其声明为 Collection<people>
.
关于java - 在静态初始值设定项中将子类添加到父类(super class)型的 ConcurrentHashMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17200675/