gpt4 book ai didi

java - 为什么这个通用方法没有给出编译时错误?

转载 作者:行者123 更新时间:2023-11-30 02:23:10 25 4
gpt4 key购买 nike

在这个程序中,我正在创建一个通用方法,其中第二个参数扩展第一个参数,但是当我将字符串作为第一个参数传递,将整数数组作为第二个参数传递时,程序也运行良好。为什么它没有给出编译时错误,因为 Integer 不扩展 String?

class GenericMethodDemo {

static <T, V extends T> boolean isIn(T x, V[] y) {

for (int i = 0; i < y.length; i++) {
if (x.equals(y[i])) {
return true;
}
}

return false;

}

public static void main(String args[]) {

Integer nums[] = {1, 2, 3, 4, 5};

if (!isIn("2", nums)) {
System.out.println("2 is not in nums");
}
}
}

最佳答案

编译不会出现错误,因为类型系统将推断两个类型参数之间最接近的公共(public)父类(super class)型。

在提供的示例中,最接近的常见父类(super class)型是 Object .

如果我们提供 double 作为第一个参数 Number将是推断类型,因为它是 Double 之间最接近的公共(public)父类(super class)型和Integer .

public static void main(String args[]) {

Integer nums[] = {1, 2, 3, 4, 5};

//In this case the nearest common type is object
if (!isIn("2", nums)) {
System.out.println("2 is not in nums");
}

//In this case the nearest common type would be Number
if (!isIn(2d, nums)) {
System.out.println("2 is not in nums");
}
}

正如 azurefrog 所说,为了防止编译类型见证 ( GenericMethodDemo.<String, Integer>isIn("2", nums) ),需要防止类型推断使用最接近的公共(public)父类(super class)型。

有关类型推断的 Java 语言规范详细信息可以在此处找到:https://docs.oracle.com/javase/specs/jls/se8/html/jls-18.html

关于java - 为什么这个通用方法没有给出编译时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46307254/

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