Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between public <T extends Animal> void addAll(List<T> animals) and public void addAll(List<Animal> animals)?

Tags:

java

generics

I am a bit confused with this, so a bit of clarification would be appreciated.

public <T extends Animal> void addAll(List<T> animals)

vs.

public void addAll(List<Animal> animals)
like image 576
secret Avatar asked Dec 24 '22 09:12

secret


1 Answers

The difference is in which type parameters in the List will be accepted by the method.

In the first method, T can be Animal or any subclass, so addAll will accept a List<Animal>, a List<Dog>, or a List<Cat>. Note that this signature is equivalent to

public void addAll(List<? extends Animal> animals)

when you don't need the exact type of Animal in the body of the method.

In the second method, you've specified that the type parameter must be Animal. Java's generics are invariant, so no subtypes of Animal will be allowed. This method will accept a List<Animal>, but not a List<Dog> or a List<Cat>.

like image 169
rgettman Avatar answered May 19 '23 12:05

rgettman