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

Nar*_*ode 7 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

[null, null, null]
[0, 1, 2]
3
Run Code Online (Sandbox Code Playgroud)

但是我在方法中test1得到的只是一个带有null元素的数组,表达式是否应该ArrayType[]::new创建一个具有指定大小的数组,并A为每个元素调用类的构造,就像Type::new在方法中使用表达式时所发生的那样test3?

Era*_*ran 12

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

就像new ArrayType[3]生成3个null引用的数组一样,调用s.apply(3)何时s是对数组构造函数的方法引用(即ArrayType[]::new)将产生3个null引用的数组.

  • 作为附录,可以通过`test1(3,i - > Stream.generate(A :: new).limit(i).toArray(A []​​ :: new))来实现所需的操作; (4认同)