gpt4 book ai didi

java - 不明确的方法调用 println char 数组和 String(而不是 Object)

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

public class Task03<K> {
public <T> T foo() {
try {
return (T) new Integer(42);
} catch (ClassCastException e) {
return (T) new Integer(43);
}
}
public static void main(String[] args) {
Task03<?> v = new Task03<>();
System.out.println(v.foo());
}
}

我在System.out.println(v.foo());行上遇到编译错误不明确的方法调用: println(char[]) 和 println(String) 都匹配

我不清楚为什么 java 尝试使用这两种方法而不是 println(Object)println(int)

我们如何理解这个java编译器的行为?

谢谢

最佳答案

Java 选择最具体适用的方法。因为<T>在调用站点确定, PrintStream.println 中的任何一个可以选择采用引用类型参数的方法。

来自JLS 15.12.2.5 :

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.

您可以传递给 println(char[]) 的任何内容或println(String)也可以传递给println(Object) ,因此前者的方法比后者更具体。因此,这些将优先于 println(Object) 选择。 .

不过,有些东西可以传给println(char[])无法传递给println(String) ,因此两者都不比另一个更具体,因此方法调用不明确。

关于java - 不明确的方法调用 println char 数组和 String(而不是 Object),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58766881/

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