gpt4 book ai didi

java - < 的用途是什么?延伸 E >

转载 作者:行者123 更新时间:2023-11-29 08:43:44 28 4
gpt4 key购买 nike

在使用泛型时,我遇到了声明 < ? extends E> .如果我以集合接口(interface)的 addAll 方法为例。

它的声明是这样的:

   interface Collection<E> {
public boolean addAll(Collection<? extends E> c);
}

所以从上面的 addAll 声明中我了解到(从不同来源读取)

  • ? extends E意味着也可以添加一个集合的所有成员,该集合的元素是 E 的子类型的任何类型

让我们来看这个例子:

List<Integer> ints = new ArrayList<Integer>();
ints.add(1);
ints.add(2);

List<? extends Number> nums = ints; // now this line works
/*
*without using ? syntax above line did not use to compile earlier
*/
List<Double> doubleList = new ArrayList<Double>();
doubleList.add(1.0);
nums.addall(doubleList); // compile time error

错误:

The method addall(List< Double >) is undefined for the type List< capture#1-of ? extends Number >

我还阅读了 O'Reilly 的“Java Generics and Collections”

In general, if a structure contains elements with a type of the form ? extends E, we can get elements out of the structure, but we cannot put elements into the structure.

所以我的问题是当我们不能用这个修改东西时,那有什么用呢?只是为了从该集合中获取元素(如果它是子类型)?

最佳答案

So my question is when we can't modify the thing with this , then what is the use ? Just to get the elements from that collection if it is a subtype ?

是的,没错。只是为了从中获取元素。

请记住 Collection<? extends Number>变量的类型,而不是集合本身的类型。通配符语法的含义更类似于特定集合必须匹配的模式,而不是“对象 X 是类型 T”意义上的类型。

如果 Java 没有通配符,您可以表达的内容就会非常受限。例如,通用 addAll方法将只接受完全相同的组件类型的集合。

关于java - < 的用途是什么?延伸 E >,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38035595/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com