是否需要在直通方法中使用有界通配符泛型? [英] Is there a need to use bounded wildcard generics in a passthrough method?

查看:235
本文介绍了是否需要在直通方法中使用有界通配符泛型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在集合< E> 的以下方法中:

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

我们使用集合<?例如:

  List< / code>那里允许一个仅存在子元素的集合。 ;驱动> drivables = new ArrayList<>(); 
列表< Car> cars = new ArrayList<>();
//我们在这里需要通配符,因为以下行:
drivables.addAll(cars);

然而,在我的后续方法中是否需要这样的有界通配符?

  public static< E>收集和LT E  - 代替; requireNonEmpty(final Collection< E> collection)抛出NoSuchElementException {
if(collection.isEmpty()){
抛出new NoSuchElementException(collection必须为非空);
}
返回集合;



$ b $ p
$ b这与 Objects.requireNonNull( T对象),它实际上返回 T对象



任何好处(或者它甚至是错误的?)写我的方法如下?

  public static< E>收集和LT ;? super E> 
requireNonEmpty(final Collection< ;? extends E> collection);


解决方案

使用集合< ?扩展E> subcollection 使传递的参数成为通用的捐助者 - 即它可以自由地读取。

需要从传递的集合中读取对象,因此不需要任何通配符。



顺便使用集合<? super E> subcollection 使其成为通用收件人 - 即可以添加到它。



请参阅何时使用extends和super 进行清晰的介绍。



泛型较低的未绑定vs较高有界通配符


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

解决方案

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.

这篇关于是否需要在直通方法中使用有界通配符泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆