哈希映射中的子类泛型?

时间:2013-06-19 16:46:21

标签: java generics collections arraylist

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

}
家庭,同事和朋友类都来自名为people的超类。为什么下面的方法不允许我使用该类作为populateMap方法的参数的参数。另外,为什么它不允许我在这里传递子类集合作为参数?

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

3 个答案:

答案 0 :(得分:3)

因为ArrayList<family>不被视为Collection<people>的子类型,因此无法分配。 Polymorphism的概念并没有像对类那样扩展到Java泛型。

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

答案 1 :(得分:3)

ArrayList<family>不被视为Collection<people>的子类型 ArrayList<family>的{​​{1}}子类型 Collection<family>

ArrayList<people>子类型

你想拥有这个

Collection<people>

答案 2 :(得分:0)

使用

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

Collection<family>应对Collection<? extends people> family延长people有效。但它可能不是你想要的,Rahul的回答是你可能想要的。