Generics (and wildcards) in Java
I'm reading a book on Java. It 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 was told that the latter code used '?' As a wildcard, it means nothing can be added to the list
Does this mean that if I have a list (or other collection type?), I can't let them accept polymorphic parameters and resize at the same time? Or did I just misunderstand something?
All help / comments are appreciated, even if they deviate slightly from the subject thank you.
Solution
No,
These two pieces of code are not completely equivalent In the first line, the method takething has the type parameter T. in the second line, you use wildcards
When you use the first version, you will specify the specific type that will be used for t Because the specific type is known, there is no problem adding it to the list
In the second version, you just say "list is an ArrayList that contains objects of unknown types that extend animal" I don't know what type it is You cannot add an object to such a list because the compiler does not have enough information (it does not know what the actual type is) to check whether you should allow what is added to the list