Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics, nested collection of wildcard

This compiles (1.6)

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

But this does not

List<List<? 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

like image 936
bpgergo Avatar asked Jun 09 '11 13:06

bpgergo


2 Answers

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 >)

like image 145
Voo Avatar answered Sep 21 '22 09:09

Voo


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 
like image 36
Michael Borgwardt Avatar answered Sep 19 '22 09:09

Michael Borgwardt