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:)
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
Please use:
public static void printList(ListableList<? extends Listable> list, String seperator){
This means that list is a readonly collections, which contains subclasses of Listable.
ListableList<Rule>
is not assign-compatible to ListableList<Listable>
because you can add non Rule objects to a ListableList<Listable>
.
Method declaration should be like printList(ListableList<? extends Listable> list, String seperator)
. Make it generic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With