A book I am reading on Java tells me that the following two pieces of code are equivalent:
public <T extends Animal> void takeThing(ArrayList<T> list)
public void takeThing(ArrayList<? extends Animal> list);
On the opposite page, I am informed that the latter piece of code uses the ‘?’ as a wildcard, meaning that nothing can be added to the list.
Does this mean that if I ever have a list (or other collection types?) that I can’t make them simultaneously accept polymorphic arguments AND be re-sizable? Or have I simply misunderstood something?
All help/comments appreciated, even if they go slightly off topic. Thanks.
No.
The two pieces of code are not completely equivalent. In the first line, the method
takeThinghas a type parameterT. In the second line, you’re using a wildcard.When you would use the first version, you would specify what concrete type would be used for
T. Because the concrete type is then known, there’s no problem to add to the list.In the second version, you’re just saying “
listis anArrayListthat contains objects of some unknown type that extendsAnimal“. What exactly that type is, isn’t known. You can’t add objects to such a list because the compiler doesn’t have enough information (it doesn’t know what the actual type is) to check if what you’re adding to the list should be allowed.