Reference method with array constructor

I tried using the reference method with the 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); } } 

Exit

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

But what I get in the test1 method is just an array with zero elements, the ArrayType[]::new expression should not create an array with the specified size and call the class A construct for each element, for example, what happens when using the Type::new expression Type::new in test3 method?

+7
java java-8 method-reference
source share
1 answer

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

Just like new ArrayType[3] creates an array of 3 null references, so calling s.apply(3) when s is a reference to an array constructor method (that is, ArrayType[]::new ) will create an array from 3 null links.

+11
source share

All Articles