在 Java 中我们可以创建 IntFunction<String[]>
来自一维数组构造函数引用:
// both do the same thing
IntFunction<String[]> createArrayL = size -> new String[size];
IntFunction<String[]> createArrayMR = String[]::new;
现在我想知道为什么我们不能用二维数组来做到这一点:
BiFunction<Integer, Integer, String[][]> createArray2DL =
(rows, cols) -> new String[rows][cols];
// error:
BiFunction<Integer, Integer, String[][]> createArray2DMR =
String[][]::new;
当然我们可以这样写:
IntFunction<String[][]> createArray2DInvalidL = String[][]::new;
System.out.println(createArray2DInvalidL.apply(3)[0]); // prints null
但这与以下行为不同:
new String[3][3]
因为行数组不会被初始化。
所以我的问题是:为什么 String[][]::new
不适用于二维数组(对我来说,这看起来像是语言设计中的不一致)?
最佳答案
确实是一个非常有趣的案例。
问题是 String[][]::new
是元数为 1 的函数(它是数组数组的构造函数),不能被视为 BiFunction(元数为 2)和您的示例 new String[3][3]
有两个参数而不是一个。
在这种情况下,
createArray2DInvalidL.apply(3)
等于调用new String[3][];
您可能正在寻找的是:
IntFunction<String[][]> createArray2D = n -> new String[n][n];
维度不需要具有相同的长度,这听起来像是一个非常合理的假设。
http://4comprehension.com/multidimensional-arrays-vs-method-references/
关于java - Java 8 中对多维数组的方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40561843/