#Generics

6 messages · Page 1 of 1 (latest)

pseudo mural
#

If class A is a child of B, would ArrayList<A> be a child of ArrayList<B>?

dim monolith
#

No, inheritance and generics are sort of separate. ArrayList<A> can contain only As, but ArrayList<B> can contain As and Bs

tight river
#

And to confuse things further, an ArrayList<? extends B> just means it's an ArrayList of B or some subclass of B, and we don't know which subclass it is, and it doesn't necessarily mean you can put B's or A's in it.

#
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        ArrayList<? extends B> list = new ArrayList<>();
        list.add(new A()); // error
        list.add(new B()); // error
    }

    private static class B {}

    private static class A extends B {}

}
#

And the other form, ArrayList<? super A> works a little differently

#
import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {
        ArrayList<? super A> list = new ArrayList<>();
        list.add(new A()); // works!
        list.add(new B()); // error
    }

    private static class B {}

    private static class A extends B {}

}