Imagine the following class hierarchy:
Cake
\- ChocolateCake
\- StuffedChocolateCake
\- VanillaCake
I want to write a method to combine Lists of ChocolateCake and VanillaCake, something like:
public static <T extends Cake> List<T> union(List<T> listA, List<T> listB) {
List<T> returnObject = new ArrayList<>();
returnObject.addAll(listA);
returnObject.addAll(listB);
return returnObject;
}
This throws a compilation error I understand:
inferred type does not conform to equality constraint(s)
I tried removing the equality constraint doing something like this:
public static List<? extends Cake> union(List<? extends Cake> listA, List<? extends Cake> listB) {
List<? extends Cake> returnObject = new ArrayList<>();
returnObject.addAll(listA);
returnObject.addAll(listB);
return returnObject;
}
I guess this is a rather basic scenario for Java Generics, what would be the right way of getting this right?
Thanks in advance for your time!
T's aren't all the same, so don't use the same letter. What you really need is more likepublic static List<Cake> union(List<T extends Cake> listA, List<U extends Cake> listB).