无法将 T 放入 Map 中。

huangapple go评论60阅读模式
英文:

Can not put a T in Map<String, ? extends T>

问题

private static final Map<String, ? extends TrackingInterface<TrackResponseObject>> map = new HashMap<>();
	static {
		map.put("dunzo", new DunzoShipment());
		map.put("self", new SelfShipment());
	}
public class DunzoShipment implements TrackingInterface<TrackResponseObject>, java.util.function.Supplier<TrackingInterface<TrackResponseObject>> { 
//body
}

在将对象放入映射中时,我遇到了一个错误:

Map<String, capture#1-of ? extends TrackingInterface> 类型中的 put(String, capture#1-of ? extends TrackingInterface) 方法不适用于参数 (String, DunzoShipment)

英文:
private static final Map&lt;String, ? extends TrackingInterface&lt;TrackResponseObject&gt;&gt; map = new HashMap&lt;&gt;();
	static {
		map.put(&quot;dunzo&quot;, new DunzoShipment());
		map.put(&quot;self&quot;, new SelfShipment());
	}
public class DunzoShipment implements TrackingInterface&lt;TrackResponseObject&gt;,java.util.function.Supplier&lt;TrackingInterface&lt;TrackResponseObject&gt;&gt; { 
//body
}

while puting the object into map i am getting an error:

> The method put(String, capture#1-of ? extends TrackingInterface<TrackResponseObject>) in the type Map<String,capture#1-of ? extends TrackingInterface<TrackResponseObject>> is not applicable for the arguments (String, DunzoShipment)

答案1

得分: 2

? extends TrackingInterface

表示“某事扩展了TrackingInterface”。我们不知道那个某事是什么,所以我们不能确定DunzoShipment是否属于其中之一。这就是为什么你不能向地图中插入。

PECS:生产者扩展,消费者 super。这是一个消费者(通过put),所以你不能使用extends

只需移除? extends部分,它就能编译通过。

英文:
? extends TrackingInterface

means "something which extends TrackingInterface". We don't know what that something is, so we can't be sure that DunzoShipment is one of them. That's why you can't insert into the map.

PECS: producer extends, consumer super. This is a consumer (via put), so you cannot use extends.

Just remove the ? extends part and it will compile.

huangapple
  • 本文由 发表于 2020年8月27日 18:10:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63613765.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定