1")-6ren">
gpt4 book ai didi

java - Java 中的泛型如何适用于以下程序?

转载 作者:太空狗 更新时间:2023-10-29 22:33:22 24 4
gpt4 key购买 nike

public class Program {

private static <Program> void foo(Program x){
System.out.println(x+"-->1");
}

private static void foo(final int i){
System.out.println(i+"-->2");
}

public static void main(String[] args) {
Integer i = 10;
foo(i);
}

}

输出是:

10-->1

我找不到关于此主题的任何相关讨论。但是,对另一个主题的回答让我有点困惑:- Return Type of Java Generic Methods

根据他们的说法,通用的 <Program>与返回类型无关,但在我的情况下,如果我如下所示对该程序进行一些更改,则输出会有所不同。

public class Program {

private static <Integer> void foo(Program x){
System.out.println(x+"-->1");
}

private static void foo(final int i){
System.out.println(i+"-->2");
}

public static void main(String[] args) {
Integer i = 10;
foo(i);
}

}

输出:

10-->2

我使用的是JDK1.7

最佳答案

在您的第一个示例中,您实际上并未指定Program 类型的参数,它是一个泛型。该类型参数与名为 Program 的类无关。打错字也会得到同样的结果:

public class Program {

private static <Programmmm> void foo(Programmmm x){
System.out.println(x+"-->1");
}

private static void foo(final int i){
System.out.println(i+"-->2");
}

public static void main(String[] args) {
Integer i = 10;
foo(i);
}

}

但是,在您的第二个示例中,参数的字面意思是 Program 类型,因此当调用 foo(10); 时它不匹配,您会得到结果来自第二种方法。

关于java - Java 中的泛型如何适用于以下程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43887401/

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