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?
java java-8 method-reference
Naruto biiju mode
source share