我尝试在以下示例中使用带有表达式ArrayType[]::new
的引用方法:
public class Main
{
public static void main(String[] args)
{
test1(3,A[]::new);
test2(x -> new A[] { new A(), new A(), new A() });
test3(A::new);
}
static void test1(int size, IntFunction<A[]> s)
{
System.out.println(Arrays.toString(s.apply(size)));
}
static void test2(IntFunction<A[]> s)
{
System.out.println(Arrays.toString(s.apply(3)));
}
static void test3(Supplier<A> s)
{
System.out.println(s.get());
}
}
class A
{
static int count = 0;
int value = 0;
A()
{
value = count++;
}
public String toString()
{
return Integer.toString(value);
}
}
输出
[null, null, null]
[0, 1, 2]
3
但是我在方法test1
中得到的只是一个带有null元素的数组,不应该表达式ArrayType[]::new
创建一个具有指定大小的数组并调用类{{1}的构造对于每个元素,比如在方法A
中使用表达式Type::new
时会发生什么?
答案 0 :(得分:12)
ArrayType[]::new
是对数组构造函数的方法引用。创建数组实例时,元素将初始化为数组类型的默认值,引用类型的默认值为null。
正如new ArrayType[3]
生成3个null
引用的数组一样,当s.apply(3)
是对数组构造函数的方法引用时,调用s
也是如此(即ArrayType[]::new
})将生成一个包含3 null
个引用的数组。