7
我试图在下面的示例中使用的参考方法用表达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
创建一个具有指定大小的数组,并为每个元素调用类A
的构造,就像使用e方法test3
中的表达式Type::new
?
谢谢您的详细和明确的解释。这是非常有帮助和可以理解的。 –
@NarutoBijuMode不客气! – Eran
作为附录,可以通过'test1(3,i - > Stream.generate(A :: new).limit(i).toArray(A [] :: new));'' – Holger