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
,因此我应该能够将子类型放入超类型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>>)
最佳答案
尝试这个:
人.java
public class people {
public class family extends people {
}
public static void main(String[] args) {
together t = new together();
System.out.println(together.registry);
}
}
Together.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class together {
private static Collection<people.family> familyList = new ArrayList<people.family>();
public static ConcurrentMap<String, Collection<? extends people>> registry = new ConcurrentHashMap<String, Collection<? extends people>>();
static {
registry.put(people.family.class.toString(), familyList);
}
}
关于java - 将子类添加到静态初始化程序中的父类(super class)型的ConcurrentHashMap中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17200675/