Java - Constructor References Array

Introduction

Arrays do not have constructors.

To use Array in Constructor References, constructors are treated to have one argument of int type that is the size of the array.

The following code shows the lambda expression and its equivalent constructor reference for an int array:

Uses a lambda expression

IntFunction<int[]> arrayCreator1 = size -> new int[size];
int[] empIds1 = arrayCreator1.apply(5); // Creates an int array of five elements

Uses an array constructor reference

IntFunction<int[]> arrayCreator2 = int[]::new;
int[] empIds2 = arrayCreator2.apply(5); // Creates an int array of five elements

You can use a Function<Integer,R> type to use an array constructor reference, where R is the array type.

Function<Integer,int[]> arrayCreator3 = int[]::new;
int[] empIds3 = arrayCreator3.apply(5); // Creates an int array of five elements

The following code creates a two-dimensional int array with the first dimension having the length of 5:

IntFunction<int[][]> TwoDimArrayCreator = int[][]::new;
int[][] matrix = TwoDimArrayCreator.apply(5); // Creates an int[5][] array

Related Topic