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

标签 java oop generics dictionary compiler-errors

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

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/

相关文章:

java - Hibernate 在充当主键的另一个实体上进行一对一映射

ios - 类型转换 SIGABRT

java - 如何避免在策略模式中使用 java 和泛型进行未经检查的强制转换

c# - 将当前对象引用为泛型类型的关键字

java - OSGI - 在新对象中注入(inject) bean

java - 为 Flex/BlazeD 设置多种 channel 类型 (AMF/AMFX)

java - Java 中是否有替代 gettext _() 方法的好方法?

.net - 为什么 System.Object 在 .NET 中不是抽象的?

java - 如何在android中搜索字符串数组?

java - 简写(1 行语句)来初始化泛型数组