带数组构造函数的引用方法

时间:2016-08-15 11:50:54

标签: java java-8 method-reference

我尝试在以下示例中使用带有表达式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时会发生什么?

1 个答案:

答案 0 :(得分:12)

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

正如new ArrayType[3]生成3个null引用的数组一样,当s.apply(3)是对数组构造函数的方法引用时,调用s也是如此(即ArrayType[]::new })将生成一个包含3 null个引用的数组。