简体   繁体   English

Java泛型:无界通配符不能与Object类型参数一起使用

[英]Java generics: Unbounded wildcard is not working with Object type argument

Explaining the issue with an example: 用一个例子解释问题:

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

I couldn't understand why "Arrays.asList(obj1)" doesn't work? 我无法理解为什么“Arrays.asList(obj1)”不起作用?

Java 7 was stupid (not it wasn't) when inferring type arguments for generic methods. 在推断泛型方法的类型参数时,Java 7是愚蠢的(不是不是)。 For example, it would use the declared type of an argument to infer the type regardless of the context of the method invocation. 例如,无论方法调用的上下文如何,它都将使用声明的参数类型来推断类型。 So in 所以

Arrays.asList(obj1);

the type argument would be inferred as 类型参数将被推断为

DataWrapper<Object>

the method's return type would then be List<DataWrapper<Object>> which is no assignable to a List<DataWrapper<?>> . 该方法的返回类型将是List<DataWrapper<Object>> ,它不能分配给List<DataWrapper<?>>

In

Arrays.asList(obj1, objInt);

the type is inferred from both arguments. 从两个参数推断出类型。 A common type is found between the two. 在两者之间发现了一种常见的类型。 In this case, that's ? extends Object 在这种情况下,那是? extends Object ? extends Object . ? extends Object The method return type becomes List<DataWrapper<? extends Object>> 方法返回类型变为List<DataWrapper<? extends Object>> List<DataWrapper<? extends Object>> which is assignable to List<DataWrapper<?>> . List<DataWrapper<? extends Object>> ,可分配给List<DataWrapper<?>>

In Java 8, what you posted works out of the box. 在Java 8中,您发布的内容是开箱即用的。 In Java 7, you can provide an explicit type argument to make it work 在Java 7中,您可以提供显式类型参数以使其工作

List<DataWrapper<?>> anyDataList = Arrays.<DataWrapper<?>>asList(obj1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM