gpt4 book ai didi

java - HashMap 中的子类泛型?

转载 作者:行者123 更新时间:2023-12-01 08:11:10 24 4
gpt4 key购买 nike

 public class people {

}

class friend extends people {

}

class coworkers extends people {

}

class family extends people {

}

public void fillMaps(){
ConcurrentMap<String, Collection<family>> familyNames = new ConcurrentHashMap<String, Collection<family>>();
ConcurrentMap<String, Collection<coworkers>> coworkersNames = new ConcurrentHashMap<String, Collection<coworkers>>();
ConcurrentMap<String, Collection<friend>> friendNames = new ConcurrentHashMap<String, Collection<friend>>();
populateMap(family.class, familyNames);
populateMap(coworkers.class, coworkersNames);
populateMap(friend.class, friendNames);
}

private <T> void populateMap(Class<T> clazz, ConcurrentMap<String, Collection<people>> map) {
if (clazz == family.class) {
map.put("example", new ArrayList<family>());
}
if (clazz == coworkers.class) {
map.put("example", new ArrayList<coworkers>());
}
if (clazz == friend.class) {
map.put("example", new ArrayList<friend>());
}

}

家庭、同事和 friend 类都从称为“人”的父类(super class)扩展而来。为什么下面的方法不允许我使用该类作为 populateMap 方法的参数的参数。另外,为什么它不允许我在这里传递子类集合作为参数?

error:
The method populateMap(Class<T>, ConcurrentMap<String,Collection<people>>) is not applicable for the arguments (Class<family>, ConcurrentMap<String,Collection<family>>)

最佳答案

ArrayList<family>不被视为 Collection<people> 的子类型 ArrayList<family> Collection<family> 的子类型 ArrayList<people> Collection<people> 的子类型

你想要这个

private <T extends people> void populateMap(ConcurrentMap<String, Collection<T>> map) {

map.put("example", new ArrayList<T>());


}

关于java - HashMap 中的子类泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17196851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com