gpt4 book ai didi

java - 为什么 HashMap> 不能转换为 HashMap>

转载 作者:行者123 更新时间:2023-11-30 02:26:11 29 4
gpt4 key购买 nike

HashMap<Integer,List<Integer>> test = new HashMap<Integer,ArrayList<Integer>>();

这一行给了我错误:HashMap<Integer,ArrayList<Integer>> cannot be converted to HashMap<Integer,List<Integer>>

我不明白为什么这不起作用。

最佳答案

底层的HashMap将仅限于ArrayList,但引用将允许您添加任何类型的列表。如果您尝试将 LinkedList 添加到 HashMap 会怎样?

也许,您只需要创建一个 ListHashMap:

HashMap<Integer, List<Integer>> test = new HashMap<Integer, List<Integer>>();

或者,如果您确实想要限制它仅包含 ArrayList:

HashMap<Integer, ArrayList<Integer>> test = new HashMap<Integer, ArrayList<Integer>>();

请注意,这种问题称为协方差和逆变。

另请参阅:

此链接是关于 C# 而不是 Java,但它是我所知道的概念的最佳解释之一。它不会以与 C# 相同的方式应用于 Java,但它仍然应该是一本有用的读物​​:

关于java - 为什么 HashMap<Integer,ArrayList<Integer>> 不能转换为 HashMap<Integer,List<Integer>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45599608/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com