把一个值放入在java中使用通配符的hashmap中不能赋值 [英] put a value into hashmap which uses wildcard in java can not assign value
问题描述
我正在学习java中的泛型。
我创建了一个Map并使用'new HashMap>()'进行了初始化。
之后,我创建了一个ArrayList放入该变量。
但是,这段代码无法编译。
错误信息是:
(String,capture#1-of?extends List)不适用于参数(String,List)
on Map.put()
我的代码如下。
package org.owls .generic.main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String [] args){
ArrayList< String> tmpArr = new ArrayList< String>();
tmpArr.add(A);
tmpArr.add(B);
列表<?> value = new ArrayList< String>(tmpArr);
地图< String,?扩展List< String>> testMap = new HashMap< String,List< String>>();
testMap.put(K,value);
}
};
我无法理解为什么编译器看起来类型,即使我分配了继承类List。
对不起,我的英文很差,编辑会受到欢迎。
感谢您的回答:D
除了 null
转换为的泛型类型?扩展...
参数。这是基本的泛型 - 因为类型参数是未知的,所以你不能放任何东西,因为你试图放置的东西不能保证是那个未知类型的子类型。
<回顾PECS(生产者
扩展
,消费者超级
)规则。 ?扩展
只能用于生产者。把东西放在消费者身上。 I am studying Generics in java. I made a Map and initialized with 'new HashMap>()'. After that, I made an ArrayList to put into that variable. However, this code can not compile.
error message is:
"The method put(String, capture#1-of ? extends List) in the type Map> is not applicable for the arguments (String, List)"
on Map.put() method.
My code is below.
package org.owls.generic.main;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
ArrayList<String> tmpArr = new ArrayList<String>();
tmpArr.add("A");
tmpArr.add("B");
List<?> value = new ArrayList<String>(tmpArr);
Map<String, ? extends List<String>> testMap = new HashMap<String, List<String>>();
testMap.put("K", value);
}
};
I can not understand why compiler looks type, even I assigned inheritanced Class which is 'List'.
Sorry for my poor English and edit will be welcomed. Thanks for your answer:D
You cannot put anything except null
into a generic type with the ? extends ...
parameter. This is basic Generics -- since the type parameter is unknown, you cannot put anything into it because whatever you try to put is not guaranteed to be a subtype of that unknown type.
Recall the PECS (Producer extends
, Consumer super
) rule. ? extends
can only be used for producers. Putting something in is a Consumer.
这篇关于把一个值放入在java中使用通配符的hashmap中不能赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!