Search code examples
javamultidimensional-arrayinitializationmemset

How to initialize all the elements of a 2D array to any specific value in java


In C++ there are a function ( memset() ) which initialize the values of a 1D array and any multidimensional-array. but in java there are a function fill which initialize the 1D array but can't initialize the multidimensional-array .


Solution

  • The Arrays.fill() method can be used to fill a 1-d array, but there's no built in method to do a "deep" fill of multi-dimensional arrays.

    For 2-d arrays I do something like this:

    int[][] arr2 = new int[5][5];  
    for(int[] arr1 : arr2) 
      Arrays.fill(arr1, 1);