繁体   English   中英

哈希映射中的子类泛型?

[英]Subclass generics in hash maps?

 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>());
        }

}

家人,同事和朋友班级都从称为人的超类扩展而来。 为什么下面的方法不允许我使用该类作为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>的子类型,因此无法分配。 Polymorphism的概念并没有像对类一样扩展到Java泛型。

private <T> void populateMap(ConcurrentMap<String, Collection<T>> map) {
    map.put("example", new ArrayList<T>());
}

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

你想要这个

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

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


    }

采用

private <T> void populateMap(Class<T> clazz, ConcurrentMap<String, Collection<? extends people>> map) {
...
}

Collection<family>应该对Collection<? extends people>有效 Collection<? extends people>作为family延伸people 但这可能不是您想要的,Rahul的答案就是您可能想要的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM