Collections 使用泛型创建集合对象
当我尝试创建对象时,如下所示:Collections 使用泛型创建集合对象,collections,java,Collections,Java,当我尝试创建对象时,如下所示: Map<Integer, Map<String, Integer>> myMap = new HashMap<Integer, HashMap<String, Integer>>(); Map myMap=newhashmap(); 语法上有什么错误,有人能解释我吗?这是类似的错误 List<Animal> list = new ArrayList<Dog>(); 如果有人试图添加Cat
Map<Integer, Map<String, Integer>> myMap = new HashMap<Integer, HashMap<String, Integer>>();
Map myMap=newhashmap();
语法上有什么错误,有人能解释我吗?这是类似的错误
List<Animal> list = new ArrayList<Dog>();
如果有人试图添加Cat
(扩展动物)对象,它将失败并抛出异常
记住animal[1]
或animal[index]
持有狗的reference
。因此Dog
参考变量可以引用Dog
对象而不是Cat
对象
所以为了避免这种情况,JSL在泛型列表/集合中做了这样的更改。此答案也适用于您的问题(Map
)参数化类型的两端应为同一类型
List<Animal> list = new ArrayList<Animal>();
List List=new ArrayList();
泛型不是共同变体。您可以使用:
Map<Integer, Map<String, Integer>> myMap = new HashMap<Integer, Map<String, Integer>>();
^ ^
--------------^------------------- becomes ------^ |
-----------------must remain as type ---------------
请注意,此语法不允许将条目添加到映射中,但作为向方法传递和从方法传递的类型很有用
一些参考资料:
Map<Integer, HashMap<String, Integer>> myMap = new HashMap<Integer, HashMap<String, Integer>>();
Map myMap=newhashmap();
您需要这样的东西:
Map<Integer, Map<String, Integer>> myMap = new HashMap<Integer, Map<String, Integer>>();
myMap.put(1, new HashMap<String, Integer>());
Map myMap=newhashmap();
put(1,newhashmap());
试试这个
Map<Integer, ? extends Map<String, Integer>> myMap = new HashMap<Integer, HashMap<String, Integer>>();
注意
Set<? extends Number> set = new HashSet<Integer>();
SetMap
与HashMap
不同。这就是问题所在
实际上HashMap实现了Map接口。所以应该是?扩展左侧的Map
您也可以使用Map myMap=new HashMap()代码>
Map<Integer, HashMap<String, Integer>> myMap = new HashMap<Integer, HashMap<String, Integer>>();
Map<Integer, Map<String, Integer>> myMap = new HashMap<Integer, Map<String, Integer>>();
myMap.put(1, new HashMap<String, Integer>());
Map<Integer, ? extends Map<String, Integer>> myMap = new HashMap<Integer, HashMap<String, Integer>>();
Set<Number> set = new HashSet<Integer>();
set.add(1.0)
Set<? extends Number> set = new HashSet<Integer>();