开发者

Java generics, nested collection of wildcard

开发者 https://www.devze.com 2023-03-11 08:25 出处:网络
This compiles (1.6) List<? extends Object> l = new ArrayList<Date>(); But this does not List<List&l开发者_C百科t;? extends Object>> ll = new ArrayList<List<Date>>(

This compiles (1.6)

List<? extends Object> l = new ArrayList<Date>();

But this does not

List<List&l开发者_C百科t;? extends Object>> ll = new ArrayList<List<Date>>();

with the error of

Type mismatch: cannot convert from ArrayList<List<Date>> to List<List<? extends Object>>

Could someone explain why? Thanks

EDIT: edited for being consequent


Well the explanations are correct, but I think it'd be a nice thing to add the actual working solution as well ;)

List<? extends List<? extends Object>>

Will work just fine, but obviously the use of such a collection is quite limited by the usual limitations of generic Collections (but then the same is true for the simpler List< ? extends Date >)


Because it would break type safety:

List<List<Object>> lo = new ArrayList<List<Object>>();
List<List<? extends Object>> ll = lo;
List<String> ls = new ArrayList<String>();
ll.add(ls);
lo.get(0).add(new Object());
String s = ls.get(0); // assigns a plain Object instance to a String reference


Suppose D is subtype of B, G<T> is a generic type

B x = new D(); // OK

G<B> y = new G<D>(); // FAIL

Now, G<Date> is a subtype of G<?>, therefore

G<?> x = new G<Date>();  // OK

G<G<?>> y = new G<G<Date>>(); // FAIL


When assigning to a variable (List<T>) with a non-wildcard generic type T, the object being assigned must have exactly T as its generic type (including all generic type parameters of T, wildcard and non-wildcard). In your case T is List<? extends Object>, which is not the same type as List<Date>.

What you can do, because List<Date> is assignable to List<? extends Object>, is use the wildcard type:

List<? extends List<? extends Object>> a = new ArrayList<List<Date>>();


<? extends Object>  

means that the wildcard could be substituted only for those objects, that are subclass of Object class.

List<List<? extends Object>> ll = new ArrayList<List<Object>>();  

gives you error of type mismatch because you are trying to assign a ArrayList of List of object of java class Object to a List that contains the List of any type of objects that are subclass of java class Object.

For more ref, have a look at the Wildcard documentation

0

精彩评论

暂无评论...
验证码 换一张
取 消