0
 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>>)
4

3 回答 3

3

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

private <T> void populateMap(ConcurrentMap<String, Collection<T>> map) {
    map.put("example", new ArrayList<T>());
}
于 2013-06-19T16:52:38.337 回答
3

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


    }
于 2013-06-19T16:54:48.077 回答
0

利用

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

Collection<family>应该对Collection<? extends people>as familyextends有效people。但这可能不是您想要的,Rahul 的答案可能是您想要的。

于 2013-06-19T16:56:14.493 回答