How to create a constructor reference for an array in Java?


A constructor reference is similar to method reference except that the name of a method is new. We can also create a constructor reference with an array type. For instance, if we need to create an integer array by using the constructor reference: int[]:: new, where the parameter is a length of an array.

Syntax

ArrayTypeName[]::new

Example

@FunctionalInterface
interface ArrayCreator {
   int[] makeArray(int number);
}
public class ArrayConstructorRefTest {
   public static void main(String[] args) {
      ArrayCreator arrayCreator = int[]::new;   // Constructor Reference for an Array
      int[] intArray = arrayCreator.makeArray(10);
      for(int i = 0; i < intArray.length; i++) {
         intArray[i] = i * i - i / 2;
         System.out.println("[" + i + "] = " + intArray[i]);
      }
   }
}

Output

[0] = 0
[1] = 1
[2] = 3
[3] = 8
[4] = 14
[5] = 23
[6] = 33
[7] = 46
[8] = 60
[9] = 77

Updated on: 14-Jul-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements