【发布时间】:2016-12-21 15:03:02
【问题描述】:
我尝试在以下示例中使用带有表达式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 中得到的只是一个带有空元素的数组,表达式ArrayType[]::new 不应该创建一个具有指定大小的数组并为每个元素调用类A 的构造,就像发生的事情一样在方法test3中使用表达式Type::new时?
【问题讨论】:
标签: java java-8 method-reference