ArrayList<A> conversion to ArrayList<B> when A implements B Java
arraylist, interface, java
Solution
try to change your method signature of printList to:
public static void printList(ListableList<? extends Listable> list, String seperator){
Generic Types are not polymorphic, I.e., `Listable<Listable>` is not a super type of `List<Rule>` even though Rule is a `sub-type` of Listable. You will have to use generics with upper bounded wildcards in your method signature to inform that your List can accept anything which is a sub-type of Listable. Note that you cannot add anything into your list if you use `Generics with upperbounded wildcards`. I.e,
public static void printList(ListableList<? extends Listable> list, String seperator){
list.add(whatever); // is not allowed
Useful Links
- An Awesome Tutorial for generics in java
Problem
I'm quite new to Java, and I have a question about method invocation conversion. I've made a new class that extends ArrayList called ListableList - but that does not seem to be the problem. The problem is I have a method that looks like this ``` public static void printList(ListableList<Listable> list, String seperator){ for(Listable item : list){ System.out.println(seperator); System.out.println(item.toList()); } System.out.println(seperator); } ``` I call this method like this: ``` Output.printList(rules, ".."); ``` Where rules is initialized as ``` rules = new ListableList<Rule>(); ``` And Rule implements Listable. When I try to compile I get: ``` required: ListableList<Listable>,String found: ListableList<Rule>,String reason: actual argument ListableList<Rule> cannot be converted to ListableList<Listable> by method invocation conversion ``` Why is this, from what I've learned, this should work?? Thanks in advance:)