gpt4 book ai didi

java - 嵌套 BiFunction 的深度(或限制,如果有的话)是多少

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

我一直在玩 BiFunction (java.util.function)。我跑了一些例子,我有一个问题。

Is there a limitation on how many times the operation can be nested with BiFunction? Is it as simple as nesting a hypothetical add(a, b) method as many times as one wants?

例如三个嵌套的 theFunction.apply()

public static int methodContainingMethod
(int a, int b, int c, BiFunction<Integer, Integer, Integer> theFunction) {
return theFunction.apply(theFunction.apply(theFunction.apply(a,b),c),c),c);
}

四个嵌套的theFunction.apply()

return
theFunction.apply(theFunction.apply(theFunction.apply(theFunction.apply(a,b),c),c),c),c);

on and on... The number of nesting can go up and on, I tested with nesting the function for over ten times.

对于需要多少嵌套,我没有确切的要求...但我很好奇可以完成多少嵌套?

最佳答案

首先,这不是特定于 BiFunction 的以任何方式。所以您基本上是在问,方法调用可以嵌套多深,简单的答案是 Java 编程语言本身没有指定限制。

有一些技术限制可能会限制数量,但这些只是技术限制,而不是规范限制。当技术在规范没有变化的情况下发展时,它们可能会被取消。

作为Alain O'Dea has explained ,方法的代码大小限制为 65535 字节或 65534 字节(如果最后一条指令应由异常处理程序覆盖)。此代码大小支持的嵌套方法调用量取决于一些因素。例如,您正在使用 interface和接口(interface)方法调用比具体类方法调用(调用虚拟指令)使用更多的字节,此外,您正在使用 BiFunction<Integer, Integer, Integer>而不是直截了当的IntBinaryOperator所以每次调用都涉及 int 的装箱需要额外代码的值。

但是无论如何还有另一个技术限制,即编译器实现。当尝试使用更高的嵌套计数编译您的示例时,javac从命令行运行,在 1500 次嵌套调用时以 stackoverflow 终止,而 Netbeans(使用与 javac 相同的编译器代码)在 IDE 开始表现出奇怪的行为之前设法编译了 2000 次嵌套调用(我猜,它不处理编译器/语法突出显示的堆栈溢出非常好)。

这表明 IDE 具有更大的堆栈大小或环境设置中的其他差异影响了表达式被解析之前的初始堆栈深度。这导致实践中没有硬性限制的结论。您可能能够编写一个编译器设法编译而没有问题的代码,而另一个编译器则退出 - 最大限度地解决这个问题并不是一个好主意。

毕竟,您的问题代码可以写成:

public static int methodContainingMethod(
int a, int b, int c, BiFunction<Integer, Integer, Integer> theFunction) {

int value = theFunction.apply(a, b);
for(int i=0; i<asDeepAsYouWannaGo; i++)
value=theFunction.apply(value, c);
return value;
}

尽管我认为,您的想法更像是:

public static int methodContainingMethod(
IntBinaryOperator theFunction, int first, int second, int... rest) {

int value = theFunction.applyAsInt(first, second);
for(int next: rest) value=theFunction.applyAsInt(value, next);
return value;
}

public static OptionalInt methodContainingMethod(
IntBinaryOperator theFunction, int... arguments) {

return IntStream.of(arguments).reduce(theFunction);
}

关于java - 嵌套 BiFunction 的深度(或限制,如果有的话)是多少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31105642/

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