Question
I understand the reasons that the java compiler will not allow us to treat a collection of type List<String>
as a List<Object>
. When I write a method designed to operate on a list containing any sort of types, I can get around this by writing
public void doToList(List<? extends Object> list) {
...
}
But, suppose that I have nested collections. Since the above method can be called on an argument of type List<String>
, I would expect the following method to be callable on an argument of type List<List<String>>
.
public void doToListOfLists(List<List<? extends Object>> list) {
// generates a compile error when invoked
}
However this generates a compile error. In order to make this method work, I needed to write its parameter as type List<? extends List<? extends Object>>
. Why?
Motivation
This seemingly unnecessary requirement has the potential to greatly obfuscate my code. For example, instead of
List<Set<Set<Set<? Object>>>>
I find myself needing to write
List<? extends Set<? extends Set<? extends Set<? Object>>>>
>`, you can add `LinkedList`s to it and break type safety.