英文:
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<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
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论