[英]What is the difference between public <T extends Animal> void addAll(List<T> animals) and public void addAll(List<Animal> animals)?
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)
The difference is in which type parameters in the List
will be accepted by the method. 不同之处在于该方法将接受
List
中的哪些类型参数。
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>
. 在第一种方法中,
T
可以是Animal
或任何子类,因此addAll
将接受List<Animal>
, List<Dog>
或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. 当你不需要方法体中确切类型的
Animal
时。
In the second method, you've specified that the type parameter must be Animal
. 在第二种方法中,您已指定type参数必须为
Animal
。 Java's generics are invariant, so no subtypes of Animal
will be allowed. Java的泛型是不变的,因此不允许使用
Animal
子类型。 This method will accept a List<Animal>
, but not a List<Dog>
or a List<Cat>
. 此方法将接受
List<Animal>
,但不接受List<Dog>
或List<Cat>
。
in simple words 'T' is an object type. 简单来说,'T'是一种对象类型。 So List 'T" type can accept any type of object whereas List of type Animal will take elements of only Animal type and not any other object.
所以List'T'类型可以接受任何类型的对象,而Animal类型的List将只接受Animal类型的元素,而不接受任何其他对象。
That's the advantage of using Generics. 这是使用泛型的优势。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.