Java Map<String,capture#1-of 类型中的方法?extends Object> 不适用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21041142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method in the type Map<String,capture#1-of ? extends Object> is not applicable
提问by Emaborsa
I have the following JAVA
method implemented due a interface:
JAVA
由于接口,我实现了以下方法:
public String importDocument(ImportSource source, Map<String, ? extends Object> paramMap);
When i try to do following, i get an compile warning. Snippet:
当我尝试执行以下操作时,会收到编译警告。片段:
paramMap.put("Key", "Value");
Error:
错误:
The method put(String, capture#1-of ? extends Object) in the type Map is not applicable for the arguments (String, String)
类型 Map 中的 put(String, capture#1-of ? extends Object) 方法不适用于参数 (String, String)
Why?
为什么?
采纳答案by Aniket Thakur
? extends Object
You are using generic wildcard. You cannot perform add operation as class type is not determinate. You cannot add/put anything(except null).
您正在使用通用通配符。您不能执行添加操作,因为类类型不确定。您不能添加/放置任何内容(空值除外)。
For more details on using wildcard you can refer oracle docs.
有关使用通配符的更多详细信息,您可以参考 oracle文档。
Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error
Since we don't know what the element type of c stands for, we cannot add objects to it. The add()
method takes arguments of type E
, the element type of the collection. When the actual type parameter is ?
, it stands for some unknown type
. Any parameter we pass to add would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type
.
因为我们不知道 c 的元素类型代表什么,所以我们不能向它添加对象。该add()
方法采用 的参数type E
,即集合的元素类型。当实际类型参数为 时?
,它代表 some unknown type
。我们传递给 add 的任何参数都必须是这种未知类型的子类型。因为我们不知道那是什么类型,所以我们不能传入任何东西The sole exception is null, which is a member of every type
。。