微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用泛型打破安全类型

如何解决使用泛型打破安全类型

当我能够破坏类型安全性时,我有以下代码

private static <T extends Number> ArrayList<T> cast2() {
    // This line compiles (1)
    return (ArrayList<T>) new ArrayList<Integer>();
}

private static ArrayList<Double> cast3() {
    // does not compile (3)
    return (ArrayList<Double>) new ArrayList<Integer>();
}

public static void main(String[] argv) {
    ArrayList<Double> ld1 = cast2();

    // This does not (2)
    ArrayList<Double> ld2 = (ArrayList<Double>) new ArrayList<Integer>();
}

很明显,第(2)行和第(3)行不是类型安全的并且不能编译。我对编译的line(1)感到困惑。在函数cast2中将Double替换为T后,与cast3相同,但cast2编译而cast3不相同。

为什么只有ArrayList 的子类型是ArrayList 本身,才能将其从ArrayList 强制转换为未知类型ArrayList

解决方法

在函数cast2中将T替换为Double后,与cast3相同,但cast2编译而cast3不相同。

因为Java泛型的工作方式不是用“ T代替Double”,而是使用擦除。泛型只是编译时的一件事。 cast2()的实际实现是

return new ArrayList();

...完全没有<Anything>cast2()编译后,您可以使用任何名称调用它,而不必担心。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。