Array Constructor References

Description

We can create an array using array constructor as follows.

ArrayTypeName::new

int[]::new is calling new int[]. new int[] requires an int type value as the array length, therefore the int[]::new needs an int type input value.

Example

The following code uses the array constructor reference to create an int array.


import java.util.Arrays;
import java.util.function.IntFunction;
/*from  ww  w.  ja  v a  2s  .  c o  m*/
public class Main{
  public static void main(String[] argv){
    IntFunction<int[]> arrayCreator1 = size ->  new int[size];
    // Creates an  int array of  five  elements
    int[] intArray1  = arrayCreator1.apply(5);
    System.out.println(Arrays.toString(intArray1));

    IntFunction<int[]> arrayCreator2 = int[]::new;
    int[] intArray2 = arrayCreator2.apply(5); 
    System.out.println(Arrays.toString(intArray2));
  }
}

The code above generates the following result.

Example 2

By using Function<Integer,ArrayType> we can specify array type in the declaration.


import java.util.Arrays;
import java.util.function.Function;
/*w ww . ja v a2s . com*/
public class Main{
  public static void main(String[] argv){
    Function<Integer,int[]>  arrayCreator3 = int[]::new;
    int[] intArray  = arrayCreator3.apply(5); 
    System.out.println(Arrays.toString(intArray));
  }
}

The code above generates the following result.

Example 3

We can specify the length for the first dimension when creating a two-dimensional array.


import java.util.Arrays;
import java.util.function.IntFunction;
//from w w  w . j av a 2s. co  m
public class Main{
  public static void main(String[] argv){
    IntFunction<int[][]> TwoDimArrayCreator  = int[][]::new;
    int[][] intArray = TwoDimArrayCreator.apply(5); 
    // Creates an  int[5][]  array
    intArray[0] = new int[5]; 
    intArray[1] = new int[5];
    intArray[2] = new int[5];
    intArray[3] = new int[5];
    intArray[4] = new int[5];
    
    System.out.println(Arrays.deepToString(intArray));
  }
}

The code above generates the following result.





















Home »
  Java Lambda »
    Java Lambda Tutorial »




Java Lambda Tutorial