Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java inheritance with parameterized Lists

I have a strange problem with inheritance and I don't understand why it should not work:

public interface A {  }

public interface B extends A {}


public class C {
void test() {
    ArrayList<A> foo = new ArrayList<B>();
    }
}

But compiling gives me the following error

Type mismatch: cannot convert from ArrayList<B> to ArrayList<A> C.java /bla/src/de/plai/test line 8 Java Problem

like image 330
plaisthos Avatar asked May 03 '26 16:05

plaisthos


1 Answers

It may seem counterintuitive at first, but even if class B is a subclass of A, a List<B> is not a subclass of List<A>. I gave a more detailed explanation and example in this earlier answer to a similar post. See also this other answer for a link to the respective item in Effective Java 2nd Edition.

The solution to this problem is using wildcards. Thus you should declare your list as

List<? extends A> foo = new ArrayList<B>();
like image 50
Péter Török Avatar answered May 05 '26 04:05

Péter Török



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!