How come in java we cannot do:
List> aList = new ArrayList>();
Even though thi
Your statement does not compile because List extends Number>
is not the same type as List
. The former is a supertype of the latter.
Have you tried this? Here I'm expressing that the List is covariant in its type argument, so it will accept any subtype of List extends Number>
(which includes List
).
List extends List extends Number>> aList = new ArrayList>();
Or even this. Here the type parameter for the ArrayList on the right-hand side is the same as the type parameter on the left-hand side, so variance is not an issue.
List> aList = new ArrayList>();
You should be able to just say
List> aList = new ArrayList>();
I tend to avoid the ?
type wildcard whenever possible. I find that the expense incurred in type annotation is not worth the benefit.