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