gpt4 book ai didi

java - javac 和 Eclipse IDE 编译器之间有趣的泛型相关差异

转载 作者:搜寻专家 更新时间:2023-11-01 03:44:00 25 4
gpt4 key购买 nike

我在 javac 和 Eclipse IDE 编译器之间有一个有趣的差异,无法弄清楚谁是对的。因此,下面的代码使用 javac 进行编译,但是 Eclipse 告诉我静态初始化程序对“exportAll”的调用是错误的,因为:

The method exportAll(Iterable< X.Stat< ? extends Number>>) in the type X is not applicable for the arguments (Collection< capture#1-of ? extends X.Stat>)

谁是对的? javac 还是 Eclipse?

import java.util.Map;

public class X {
interface Stat<T> {
}

public static void exportAll(Iterable<Stat<? extends Number>> vars) {
}

public static Map<Double, ? extends Stat> getPercentiles() {
return null;
}

static {
exportAll(getPercentiles().values());
}

最佳答案

您无法编译示例 - 您正在调用非静态方法 getPercentiles来自静态初始值设定项,所以我假设它也是一个静态方法。

无论如何,如果您使用-XLint:unchecked 进行编译,您的编译器至少会发出“未检查”警告。 (Stat 采用类型参数!)。我假设您想要以下内容:

public class X {
interface Stat<T> {
}

public static void exportAll(Iterable<? extends Stat<? extends Number>> vars) {
}

public static Map<Double, ? extends Stat<Double>> getPercentiles() {
return null;
}

static {
exportAll(getPercentiles().values());
}

我假设您的百分位数是 Stat<Double> 的任意子类,因此我将它们声明为 ? extends Stat<Double>在 map 中。所以 values()调用将返回 Collection<? extends Stat<Double>> .

Collection工具 Iterable ,因此我们在那一边是安全的。但是Collection<? extends Stat<Double>>不在 Iterable<Stat<? extends Number>> 范围内,因此我们需要将参数声明为 Iterable<? extends Stat<? extends Number>> .

拥有 exportAll 的美妙之处(好吧,语法除外)拿Iterable<? extends Stat<? extends Number>>是你的Map可能包含各种 ? extends Stats<N>其中 NNumber 的子类.

关于java - javac 和 Eclipse IDE 编译器之间有趣的泛型相关差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7264960/

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