Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference method with array constructor [duplicate]

I tried to use reference method with expression ArrayType[]::new in the following example:

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);
    }
}

Output

[null, null, null]
[0, 1, 2]
3

But what i get in method test1 is only an array with null elements, shouldn't the expression ArrayType[]::new create an array with the specified size and call the construction of class A for each element like what happen when using expression Type::new in method test3?

like image 909
Naruto Biju Mode Avatar asked Aug 15 '16 11:08

Naruto Biju Mode


1 Answers

ArrayType[]::new is a method reference to an array constructor. When you create an instance of an array, the elements are initialized to the default value for the array's type, and the default value for reference types is null.

Just as new ArrayType[3] produces an array of 3 null references, so does calling s.apply(3) when s is a method reference to an array constructor (i.e. ArrayType[]::new) would produce an array of 3 null references.

like image 168
Eran Avatar answered Nov 14 '22 22:11

Eran