gpt4 book ai didi

generics - 奇怪的 JDK 行为,它应该编译吗?

转载 作者:行者123 更新时间:2023-12-02 08:41:49 24 4
gpt4 key购买 nike

import java.util.*;

public class Main <T> {

public void guru(List<Integer> list) {
System.out.println("INteger");
}

public static void main(String[] args) {
List<String> list = new ArrayList<String>();
new Main().guru(list);
}
}

在我看来,调用

guru(List<String>); //no type erasure during compiling...

应该会导致编译失败。

这就是我们创建对象时会发生的情况:

new Main<Integer>() //or any other type

谁能告诉我这是怎么回事?那是JDK中的错误或不带参数实例化参数化对象可能会导致此类问题,为什么?

如果我们将 Main 定义更改为:

public class Main {

如预期的那样编译失败。

最佳答案

问题出在这里:

new Main().guru(list);
^^^^

您使用 Main 的原始版本(没有泛型),因此所有泛型信息都将被忽略。不过,您应该会收到编译器警告。

如果你尝试:

new Main<SomeType>().guru(list);

你应该得到一个编译错误。

更准确地说,当使用原始类型时:new Main(),会执行类型删除,这不仅会删除类型本身的通用信息,还会删除 also from its methods :

The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C [...] is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.

关于generics - 奇怪的 JDK 行为,它应该编译吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15926174/

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