Java 中的逆变和继承有什么区别?

What's the difference between contravariance and inheritance in Java?

我有一个父 class A 和它的子 class B。这两个片段有什么区别:

    public static void main (String[] args) {
        ArrayList<? super A> e = new ArrayList<>();
        B thing = new B();
        e.add(thing);
        System.out.println(e.get(0));
    }
    public static void main (String[] args) {
        ArrayList<A> e = new ArrayList<>();
        B thing = new B();
        e.add(thing);
        System.out.println(e.get(0));
    }

ArrayList<? super A>ArrayList<A>的区别在于,前者可以赋给ArrayList<T>的对象,其中TA的超类或者A 本身。

具体来说,这是有效的:

ArrayList<? super A> listOfSuperA = new ArrayList<Object>();

这不是:

ArrayList<A> listOfA = new ArrayList<Object>();

这意味着您可以从 listOfAlistOfSuperA 中获取不同类型的值:

A a = listOfA.get(0); // valid
Object o = listOfA.get(0); // valid, because A can be converted to Object.
A a2 = listOfSuperA.get(0); // invalid, because listOfSuperA could contain Objects, which are not convertible to A
Object o2 = listOfSuperA.get(0); // valid, because whatever is in listOfSuperA, it can be converted to Object

This might be useful if you want to learn more about where to use ? super T