为什么将ArrayList的泛型转换为超类不起作用?

为什么将ArrayList的泛型转换为超类不起作用?

问题描述:

有人可以向我解释为什么标记为 //的行给出了编译错误(为什么?)在下面的代码示例不工作?

Can someone please explain to me why the line marked //this line gives a compile error (why?) in the following code sample does not work?

import java.util.ArrayList;

public class GenericCastCheck {

    class A{
    }

    class B extends A{
    }

    public static void main(String[] args) {

        A aObject = new A();
        B bObject = new B();

        //this line works fine
        aObject = bObject;
        //this line gives a compile (expected)
        bObject = aObject;

        ArrayList<A> aList = new ArrayList<A>();
        ArrayList<B> bList = new ArrayList<B>();

        //this line gives a compile error (why?)
        aList = bList;
        //this line gives a compile error (expected)
        bList = aList;
    }
}

具体来说,当我们说 bList ArrayList< B> 类型,并不意味着它的每个元素都是 B ?如果是,那么如果我们可以转换 B 的个别实例,则将它转换为 ArrayList >

Specifically, when we say that bList is of type ArrayList<B>, does it not mean that each element of it is an instance of B? If so, then what is the problem in casting it to ArrayList<A>, if we can cast individual instances of B to A?

感谢。

问题是这个:

ArrayList<A> aList = new ArrayList<A>();
ArrayList<B> bList = new ArrayList<B>();
aList = bList; // if this were valid...
aList.add(new A()); // ...what should happen here?
B b = bList.get(0); // ...and here?

如果你对数组做同样的事情,你会在运行时在第4行得到一个ArrayStoreException。对于通用集合,决定在编译时阻止这种事情。

If you do the same thing with arrays, you get an ArrayStoreException in line 4 at runtime. For generic collections, it was decided to prevent that kind of thing at compile time.