举例说明问题:
public class DataWrapper<T> {
T data;
};
DataWrapper<Object> obj1 = new DataWrapper<Object>();
List<DataWrapper<?>> anyDataList = Arrays.asList(obj1); //this doesn't work
DataWrapper<Integer> objInt = new DataWrapper<Integer>();
anyDataList = Arrays.asList(obj1, objInt); //this work
我不明白为什么“Arrays.asList(obj1)”不起作用?
最佳答案
在为泛型方法推断类型参数时,Java 7 很愚蠢(但事实并非如此)。例如,无论方法调用的上下文如何,它都会使用参数的声明类型来推断类型。所以在
Arrays.asList(obj1);
类型参数将被推断为
DataWrapper<Object>
该方法的返回类型将是 List<DataWrapper<Object>>
不可分配给 List<DataWrapper<?>>
.
在
Arrays.asList(obj1, objInt);
类型是从两个参数推断出来的。两者之间有一个共同的类型。在这种情况下,这是 ? extends Object
.方法返回类型变为 List<DataWrapper<? extends Object>>
可分配给 List<DataWrapper<?>>
.
在 Java 8 中,您发布的内容开箱即用。在 Java 7 中,您可以提供一个显式类型参数以使其工作
List<DataWrapper<?>> anyDataList = Arrays.<DataWrapper<?>>asList(obj1);
关于Java 泛型 : Unbounded wildcard is not working with Object type argument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25535579/