Is there a need to use bounded wildcard generics in a passthrough method?

[亡魂溺海] 提交于 2019-12-08 08:39:24

问题


I know that in the following method in Collection<E>:

public void addAll(Collection<? extends E> subcollection);

We use Collection<? super E> there to allow a collection that solely exists of sub-elements, example:

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.

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);

回答1:


The use of Collection<? extends E> subcollection makes the passed parameter a universal donor - i.e. it can be read from with freedom.

You do not need to read objects from the passed collection so you do not need any wildcards.

Incidentally using Collection<? super E> subcollection makes it a universal recipient - i.e. you can add to it.

See When to use extends and super for a clear introduction.

Also a good answer covering this Generic lower unbound vs upper bounded wildcards.



来源:https://stackoverflow.com/questions/23199488/is-there-a-need-to-use-bounded-wildcard-generics-in-a-passthrough-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!