Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Can';t为接口实现者创建泛型_Java_Oop_Generics_Map_Compiler Errors - Fatal编程技术网

Java Can';t为接口实现者创建泛型

Java Can';t为接口实现者创建泛型,java,oop,generics,map,compiler-errors,Java,Oop,Generics,Map,Compiler Errors,我试图创建一种服务定位器类,其中有 Map 但我以后做不到 myMap.put(0x00,newsomethingimplementor()) 当我得到一个错误时:(18,33)java:不兼容的类型:org.sample.SomethingImplementor无法转换为捕获#1 of?扩展其他内容 我的班级结构如下: public interface ISomething { public void doSomething(); } public class SomethingIm

我试图创建一种服务定位器类,其中有

Map

但我以后做不到

myMap.put(0x00,newsomethingimplementor())

当我得到一个
错误时:(18,33)java:不兼容的类型:org.sample.SomethingImplementor无法转换为捕获#1 of?扩展其他内容

我的班级结构如下:

public interface ISomething {
    public void doSomething();
}

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

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

不要使用未知类型

Map<Integer, ISomething> map;
Map;
使用未知类型不会得到任何结果,只需指定
ISomething
就足够了,这是正确的选择


此外,泛型类型必须完全匹配;ie
?扩展ISomething
与ISomething

的类型不同。您根本不需要通配符

您可以直接使用

Map<Integer, ISomething>
Map
您可以实现
ISomething
的每个子类

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

列表是有界通配符的一个示例。这个表示未知类型,就像我们前面看到的通配符一样。然而,在本例中,我们知道这个未知类型实际上是Shape的一个子类型。(注意:它可以是Shape本身,也可以是某个子类;它不需要逐字扩展Shape。)我们说Shape是通配符的上限

与往常一样,使用通配符的灵活性需要付出代价。这个代价是,现在在方法体中写入形状是非法的。例如,这是不允许的:

您应该能够理解为什么上面的代码是不允许的。shapes.add()的第二个参数的类型是?扩展形状--形状的未知子类型。因为我们不知道它是什么类型,所以我们不知道它是否是矩形的超类型;它可能是也可能不是这样的超类型,因此在那里传递矩形是不安全的

通配符: