哈希映射中的子类泛型?

编程入门 行业动态 更新时间:2024-10-25 02:23:54
本文介绍了哈希映射中的子类泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..
 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 07:35:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/881933.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子类

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!