Short question about '? extends': Why does this code not compile?
Hi,
I would like to know, why this code does not compile:
ArrayList<?extends Object> array;
array.add(new Object());
It doesn't look very dangerous to me. I restrict the array to be an array of "at least Object", so I assume that I can add Objects to it, even though it is not the case.
Bug or feature? ;-)
Regards
Daniel
Feature.
? extends Object doesn't mean "anything that extends Object" (which is how most people read it at first), it means "some fixed subclass of Object which I don't know right now".
In this case, you could do:
ArrayList<? extends Object> array = new ArrayList<Integer>();
and now your second line makes no sense whatsoever.
ArrayList<? super Object> array;
array.add(new Object());
Note that the above will compile. The tradeoff here is that you can only treat things you retrieve from it as Object even if you said super Map, for example.
Hello and thanks for the quick reply!
I think I can understand that. Now please allow this followup question: Why does it not mean "anything that extends Object"?
I do now understand the technical reason why my code did not compile, but i don't see the design decision, why this is handled that way. I assume there is a reason for it, (because otherwise it would have been made "anything that extends Object" from the start), but I just don't know it right now.
Regards
Daniel
If you want a collection of anything that extends Object, simply define:
ArrayList<Object> array;
array.add(new Object());
what the wildcard says instead is: create a collection of some specific subtype of Object, which is left undetermined at this point. Remember that List<Number> isn't compatible with List<Object>. So this is where the wildcard becomes interesting to abstract algorithms for various typed collection.
muleta at 2007-7-14 21:51:21 >
