gpt4 book ai didi

java - 无法为接口(interface)实现者创建泛型

转载 作者:行者123 更新时间:2023-11-30 08:21:26 25 4
gpt4 key购买 nike

我正在尝试创建一种服务定位器类,其中有一个

Map<Integer, ? extends ISomething>

但我以后不能做

myMap.put(0x00, new SomethingImplementor())

当我得到一个 Error:(18, 33) java: incompatible types: org.sample.SomethingImplementor cannot be converted to capture#1 of ? extends ISomething

我的类结构如下:

public interface ISomething {
public void doSomething();
}

public class SomethingImplementor implements ISomething {
@Override public void doSomething() {...}
}

为什么我不能创建此 map 并将值放入其中?

最佳答案

您根本不需要通配符。

可以直接使用

Map<Integer, ISomething>

并且您可以实现 ISomething 的每个子类。

无论如何,在这种情况下要使用通配符,您应该使用 super。使用 extends,您不知道它将是什么类型,因此您无法向 map 添加任何内容。

List is an example of a bounded wildcard. The ? stands for an unknown type, just like the wildcards we saw earlier. However, in this case, we know that this unknown type is in fact a subtype of Shape. (Note: It could be Shape itself, or some subclass; it need not literally extend Shape.) We say that Shape is the upper bound of the wildcard.

There is, as usual, a price to be paid for the flexibility of using wildcards. That price is that it is now illegal to write into shapes in the body of the method. For instance, this is not allowed:

You should be able to figure out why the code above is disallowed. The type of the second parameter to shapes.add() is ? extends Shape-- an unknown subtype of Shape. Since we don't know what type it is, we don't know if it is a supertype of Rectangle; it might or might not be such a supertype, so it isn't safe to pass a Rectangle there.

通配符:http://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html

关于java - 无法为接口(interface)实现者创建泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25213635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com