fails to compile
incompatible types: List<CAP#1> cannot be converted to List<? extends Building>
where CAP#1 is a fresh type-variable: CAP#1 extends Object super: Residential from
capture of ? super Residential
There are three kinds of actuaries: those who can count, and those who can't.
the 'So the compiler cannot guarantee that '? extends Building' is correct, and therefore it won't compile.
There are three kinds of actuaries: those who can count, and those who can't.
Stephen Bell wrote:
Then let's say I create a List with a Lower Bounded type...
There are three kinds of actuaries: those who can count, and those who can't.
Henry Wong wrote:
Can someone with deep knowledge of generics explain this one? First, it is using the diamond operator. This means that the type of the generics (that is being instantiated) is inferred. However, it is also using the wildcard. So, what is the type of the generic? How is it inferred? I have seen code like this before, and this always bothered me....
Piet Souris wrote:But if you have [...] then [...] also fails.
It is not clear to me what the compiler does with things like ? super/extends, so I try to avoid these things if that is at all possible.
Stephan van Hulst wrote:It's very simple. The diamond operator just removes the wildcard. In Java 9 ....
Stephan van Hulst wrote:
Piet Souris wrote:But if you have [...] then [...] also fails.
That's because myList could be of any type that is a super-type of Residential, including List<Object>. You can't assign a List<Object> to a List<Residential>, so the compiler complains.
Stephan van Hulst wrote:That's a pity. Wildcards make your libraries much more flexible and easy to use. You should use them as much as possible.
There are three kinds of actuaries: those who can count, and those who can't.
Piet Souris wrote:That's right, but it would have been possible for the compiler to conclude that [..] the left part (? super Residential) could only be Residential, but that is obviously not what is happening.
I guess that in your profession you are dealing much more with this subject than I do. I guess it is also something to get used to. I wil try to make more use of this in the future!
Stephen Bell wrote:So, the above list can only really be of type 'SemiDet' as that is the 'lowest' class in my hierarchy, ie, it has no subclasses.
Paul Clapham wrote:
I don't believe the compiler will look through your class hierarchy
Consider Paul's rocket mass heater. |