Posts

Showing posts with the label generics

Why can't I use Stream#toList to collect a list of a class' interface in Java 16?

17 6 I'm streaming objects of a class implementing an interface. I'd like to collect them as a list of elements of the interface, rather than the implementing class. This seems impossible with Java 16.0.1's Stream#toList method. For example in the code below, the last statement will fail to compile. import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class WhyDodo { private interface Dodo { } private static class FancyDodo implements Dodo { } public static void main(String[] args) { final List<Dodo> dodos = Stream.of(new FancyDodo()).collect(Collectors.toList()); final List<FancyDodo> fancyDodos = Stream.of(new FancyDodo()).toList(); final List<Dodo> n...

What is a real life example of generic

I understand that <? super T> represents any super class of T (parent class of T of any level). But I really struggle to imagine any real life example for this generic bound wildcard. I understand what <? super T> means and I have seen this method: public class Collections { public static <T> void copy(List<? super T> dest, List<? extends T> src) { for (int i = 0; i < src.size(); i++) dest.set(i, src.get(i)); } } I am looking for an example of real life use case where this construction can be used and not for an explanation of what it is. The easiest example I can think of is: public static <T extends Comparable<? super T>> void sort(List<T> list) { list.sort(null); } taken from the same Collections. This way a Dog can implement Comparable<Animal> and if Animal already implements that, Dog does not have to do anything. EDIT for a real example: After some email ping-pongs, I am allowed to present a real e...