Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList<A> conversion to ArrayList<B> when A implements B Java

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:)

like image 908
Simon Malone Avatar asked Mar 11 '13 12:03

Simon Malone


3 Answers

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
like image 63
PermGenError Avatar answered Nov 11 '22 04:11

PermGenError


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>.

like image 45
Hendrik Brummermann Avatar answered Nov 11 '22 04:11

Hendrik Brummermann


Method declaration should be like printList(ListableList<? extends Listable> list, String seperator). Make it generic.

like image 1
Jeevan Patil Avatar answered Nov 11 '22 03:11

Jeevan Patil