java Double::is Finite与Double::is Infinite有何不同?

agyaoht7  于 2022-12-28  发布在  Java
关注(0)|答案(2)|浏览(242)

下面的代码:

class Result {
    public Result(long infiniteCount, DoubleSummaryStatistics statistics) {
        this.infiniteCount = infiniteCount;
        this.statistics = statistics;
    }
    final long infiniteCount;
    final DoubleSummaryStatistics statistics;
}

这将编译:

Result result = DoubleStream.of(1.0, 2.0, 3.0).boxed().collect(Collectors.teeing(
        Collectors.filtering(Double::isFinite, Collectors.counting()),
        Collectors.filtering(Double::isFinite, Collectors.summarizingDouble(d -> d)),
        Result::new));

这不会:

Result result = DoubleStream.of(1.0, 2.0, 3.0).boxed().collect(Collectors.teeing(
        Collectors.filtering(Double::isInfinite, Collectors.counting()),
        Collectors.filtering(Double::isFinite, Collectors.summarizingDouble(d -> d)),
        Result::new));

编译结果如下:
java:不兼容的类型:无法推断类型变量T,A,R,capture#1 of?,T(参数不匹配;对isInfinite的无效方法引用引用不明确,java.lang.Double中的方法isInfinite(double)和java.lang.Double中的方法isInfinite()均匹配
Here is the source code of these 2 methods from Double.java of Java 19... I don't understand why is there difference... (AFAIK @IntrinsicCandidate shouldn't affect this, and otherwise it's just two methods that return a boolean).

@IntrinsicCandidate
public static boolean isInfinite(double v) {
    return (v == POSITIVE_INFINITY) || (v == NEGATIVE_INFINITY);
}

public static boolean isFinite(double d) {
    return Math.abs(d) <= Double.MAX_VALUE;
}

那么,为什么第一个编译而第二个没有...?

deyfvvtc

deyfvvtc1#

缺少非静态Double.isInfinite()方法:

public boolean isInfinite() {
    return isInfinite(value);
}

这使得Double::isInfinite不明确,因为两个方法都匹配。你可以使用lambda来消除它的不明确性:

Collectors.filtering(d -> d.isInfinite(), Collectors.counting())
gmol1639

gmol16392#

isInfinite作为静态和示例方法存在:

  • static boolean isInfinite(double d)
  • boolean isInfinite()

你的方法引用变得不明确。通过转换为lambda,你可以消除歧义:

Result result = DoubleStream.of(1.0, 2.0, 3.0).boxed().collect(Collectors.teeing(
        Collectors.filtering(d -> d.isInfinite(), Collectors.counting()),
        Collectors.filtering(Double::isFinite, Collectors.summarizingDouble(d -> d)),
        Result::new));

相关问题