哈希映射中的子类泛型? [英] Subclass generics in hash maps?

查看:25
本文介绍了哈希映射中的子类泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

}

family、coworkers 和friend 类都从称为people 的超类扩展而来.为什么下面的方法不允许我使用类作为 populateMap 方法参数的参数.另外,为什么它不允许我在这里将子类集合作为参数传递?

family, coworkers, and friend classes all extend from the superclass called people. Why doesn't the method below allow me to use the class as an argument to the parameters of the populateMap method. Also, why doesn't it allow me to pass a subclass collection as an argument here?

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

推荐答案

ArrayList 不被视为 Collection 的子类型ArrayList Collection 的子类型ArrayList Collection

ArrayList<family> isn't considered as a subtype of Collection<people> ArrayList<family> subtype of Collection<family> ArrayList<people> subtype of Collection<people>

你想要这个

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

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


    }

这篇关于哈希映射中的子类泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆