gpt4 book ai didi

java - 为什么不能用 Java 实现泛型数组?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:32:23 25 4
gpt4 key购买 nike

<分区>

Java 使用类型删除

据我了解new ArrayList<String>()被转换成它的原始类型,并且使用了大量语法糖来假装这个 Object 的 ArrayList 就像一个 String 的 ArrayList。 Java 将此称为类型删除。

例如

这是我用 Java 写的:

public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList<>();
stringList.add("foo");
String s = stringList.get(0);
}

当我反编译字节码时,我得到了这个:

public static void main(String[] args) {
ArrayList<String> stringList = new ArrayList();
stringList.add("foo");
String s = (String)stringList.get(0);
}

因此

为什么不能 new T[]转换为 (T[]) new Object[] 自动,使用相同的 “shtick” 编译器提取类型删除?

请不要让我回答这个问题:What's the reason I can't create generic array types in Java?特别是这条评论:

The problem is deeper than pointed in that answer, so further investigation is needed. As you said type info is erased and in compiled code we have no difference between two generic types - all we have is base type - so why for T[] - compile to Object[]. In this case everything will be fine - array will remember that it was created with object type and will let save all types. However as for me the real problem is that arrays are covariant meaning that Animal[] can be assigned to Object[]. On the other hand generics are not ArrayList<Animal> can not be assigned to ArrayList<Object>

因为这个逻辑是有缺陷的!

这里有两个过程。

  1. 编译器对 ArrayList<String> 实现“人工” 不变性.

  2. 编译器转换 Object进入T .

同样,为什么不能使用构成所有泛型的简单语法糖在 Java 中实现泛型数组,同时保持数组的正常协变性?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com