java - 为什么将 ArrayList 的泛型转换为父类(super class)不起作用?

标签 java generics casting

有人可以向我解释为什么标记为 //this line gives a compile error (why?) 的行吗?在下面的代码示例中不起作用?

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的一个实例?如果是这样,那么将其转换为 ArrayList<A> 的问题是什么? , 如果我们可以转换 B 的个别实例至 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。对于泛型集合,决定在编译时防止此类事情发生。

关于java - 为什么将 ArrayList 的泛型转换为父类(super class)不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6044329/

相关文章:

java - 使用 Maven Shade 插件时出现 ClassNotFound 异常

java - 当文本字段聚焦时,Windows 平板电脑触摸键盘不会弹出

c - Short to Char 类型转换

Java float 自动舍入问题

java - 在 JTextArea 中突出显示字符串

java - 使用连续字符键的通用二分搜索失败

c# - 当你只知道通用基类的类型时,如何找到通用基类的派生类?

c# - 为什么在字典声明中使用接口(interface)?

java - JAVA 中的内部转换是如何工作的?原始和引用转换

php - 在php中将字符串转换为整数时返回零