gpt4 book ai didi

java - 通用类型不匹配

转载 作者:行者123 更新时间:2023-12-01 10:10:00 25 4
gpt4 key购买 nike

class GenMethDemo {
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;
}

/*when compiled in java 7 it producing an error and compiling in java 8 without error */
public static void main(String args[]) {
Integer nums[] = {1, 2, 3, 4, 5};
String s[] = {"one", "two", "three"};
System.out.println(isIn("fs", nums));
/*
when compiled in java 7 it producing an error and compiling in java 8 without error */
}
}

最佳答案

这是由于 Java 8 中广义目标类型推理的改进。实际上,我上周回答了类似的问题。 Java 8 call to generic method is ambiguous

问题第一个答案Java 8: Reference to [method] is ambiguous也很好。

Java 8 能够推断传递给泛型方法的参数类型。因此,正如 @Thomas 在他的评论中所说,类型 T 被推断为 Object,而 V 被推断为扩展的对象对象,因此整数。在 Java 7 中,这只会引发错误,因为 Integer 显然不会扩展 String

关于java - 通用类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36181800/

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