2016-08-15 59 views
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

回答

11

ArrayType[]::new是一个引用数组构造函数的方法。在创建数组的实例时,元素将初始化为数组类型的默认值,而引用类型的默认值为null。

正如new ArrayType[3]产生的3个null引用数组,所以不调用s.apply(3)s是一种方法参照数组构造(即ArrayType[]::new)将产生的3所null引用的数组。

+0

谢谢您的详细和明确的解释。这是非常有帮助和可以理解的。 –

+1

@NarutoBijuMode不客气! – Eran

+3

作为附录,可以通过'test1(3,i - > Stream.generate(A :: new).limit(i).toArray(A []​​ :: new));'' – Holger