[英]Is there a need to use bounded wildcard generics in a passthrough method?
I know that in the following method in Collection<E>
: 我知道在Collection<E>
的以下方法中:
public void addAll(Collection<? extends E> subcollection);
We use Collection<? super E>
我们使用Collection<? super E>
Collection<? super E>
there to allow a collection that solely exists of sub-elements, example: Collection<? super E>
允许仅存在子元素的集合,例如:
List<Drivable> drivables = new ArrayList<>();
List<Car> cars = new ArrayList<>();
//we need the wildcard here, because of the following line:
drivables.addAll(cars);
However, are such bounded wildcards needed in my following method? 但是,我的以下方法是否需要这种有界通配符?
public static <E> Collection<E> requireNonEmpty(final Collection<E> collection) throws NoSuchElementException {
if (collection.isEmpty()) {
throw new NoSuchElementException("collection must be non-empty");
}
return collection;
}
This uses a similar idiom as Objects.requireNonNull(T object)
, which actually returns the T object
. 这使用与Objects.requireNonNull(T object)
类似的惯用法,该惯用法实际上返回T object
。
So, is there any benefit (or is it even wrong?) to write my method as the following? 因此,将我的方法编写为以下内容是否有任何好处(甚至是错误的?)?
public static <E> Collection<? super E>
requireNonEmpty(final Collection<? extends E> collection);
The use of Collection<? extends E> subcollection
使用Collection<? extends E> subcollection
Collection<? extends E> subcollection
makes the passed parameter a universal donor - ie it can be read from with freedom. Collection<? extends E> subcollection
使传递的参数成为通用施主 -即可以自由读取。
You do not need to read objects from the passed collection so you do not need any wildcards. 您不需要从传递的集合中读取对象,因此不需要任何通配符。
Incidentally using Collection<? super E> subcollection
顺便使用Collection<? super E> subcollection
Collection<? super E> subcollection
makes it a universal recipient - ie you can add to it. Collection<? super E> subcollection
使其成为通用收件人-即您可以添加到其中。
See When to use extends and super for a clear introduction. 有关清楚的介绍,请参见何时使用扩展和超级 。
Also a good answer covering this Generic lower unbound vs upper bounded wildcards . 涵盖此通用较低未绑定vs较高边界通配符的好答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.