Solution to b33f: Bounded generic methods with streams
See code at solutions/code/tutorialquestions/question11e2
Compare the sample source code for this question with your solution.
The signature of the method is:
public static <E, C extends Collection<E>> Optional<C> getSmallestCollection(List<C> collections);
Unpicking this a bit, the E
is the element type of the collections in the list of collections. A simpler method signature is:
public static <E> Optional<Collection<E>> getSmallestCollection(List<Collection<E>> collections);
but this only works if we pass in a List<Collection<E>>
; we cannot pass in a List<Set<E>>
for example.
The purpose of C extends Collection<E>
is to say that "C
is any type that is a subtype of Collection<E>
, or Collection<E>
itself". The true method signature is the same as the simplified method signature, except that C extends Collection<E>
is introduced right after E
is introduced, and then C
is used instead of Collection<E>
thereafter.
The solution has a couple of comments starting: "Think about why ..." -- take a look at these and have a think!