gpt4 book ai didi

Java 泛型 : solution of "Core Java" tutorial is not working on Eclipse?

转载 作者:行者123 更新时间:2023-12-01 07:11:44 24 4
gpt4 key购买 nike

我正在阅读 Hortsmann 和 Cornell 合着的书“Core Java”(第 1 卷)。在“泛型”一章中,他们建议故意输入错误的输入,以便查看编译器所说的内容。我的问题是:编译器不仅不会给我同样的错误,而且当我按照书中所述更正输入时,它也会继续给我错误。交易如下:

public class PairTest1 {
public static void main(String[] args) {
double middle = ArrayAlg.getMiddle(3.14, 1729, 0);
}
}

class ArrayAlg {
public static <T> T getMiddle(T[] a) {
return a[a.length / 2];
}
}

书上说我应该得到错误:

found: java.lang.Number&java.lang.Comparable>, required: double.

相反,Eclipse 不会让我运行该程序,并表示

The method getMiddle(T[]) in the type ArrayAlg is not applicable for the arguments (double, int, int)

书上接着说

the remedy is to write all parameters as double values.

因此,我将 1729 更改为 1729.1,将 0 更改为 0.1。现在 Eclipse 说:

The method getMiddle(T[]) in the type ArrayAlg is not applicable for the arguments (double, double, double)

嗯...我不明白发生了什么事。有建议吗?

谢谢您并致以问候

编辑:我尝试创建数组 double[] doubles = { 3.14, 1729.1, 0.1 }; 并将其作为参数,但现在我收到错误 The method getMiddle ArrayAlg 类型中的 (T[]) 不适用于参数 (double[])

最佳答案

您应该将调用更改为

double middle = ArrayAlg.getMiddle(new Double[]{ 3.14, 1729.0, 0.0 });

如果你想按照你现在的方式传递它们,那么你应该将声明更改为

public static <T> T getMiddle(T... a)
{
return a[a.length / 2];
}

使用Java的var-arg语法。然后您可以将该方法调用为

double middle = ArrayAlg.getMiddle(3.14, 1729.0, 0.0);

关于Java 泛型 : solution of "Core Java" tutorial is not working on Eclipse?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12863979/

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