How to set default value of a 2D array?

Hi!
When I used to use 2D fixed arrays (int[][], or int[] for that matter) it was always a bit annoying setting the values. Like default boolean state in an array is false. Is it possible to set it to something else without using

int w = 10, h = 10, defaultValue = 123;
int grid[][] = new int[w][h];
for(int i = 0;i < w; i++) for(int j = 0; j < h; j++) grid[i][j] = defaultValue;

Nope! If it’s primitive type default value is 0 and false for boolean.
For non-primitive types default value is null.
docs.Oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

2 Likes


// int w = 10, h = 10,
final int defaultValue = 123;

int grid[][] = {
  { defaultValue, defaultValue, defaultValue, defaultValue, defaultValue}, 
  { defaultValue, defaultValue, defaultValue, defaultValue, defaultValue}, 
  { defaultValue, defaultValue, defaultValue, defaultValue, defaultValue}, 
  { defaultValue, defaultValue, defaultValue, defaultValue, defaultValue}, 
  { defaultValue, defaultValue, defaultValue, defaultValue, defaultValue}, 
  { defaultValue, defaultValue, defaultValue, defaultValue, defaultValue}
};

size(660, 660); 

for (int i = 0; i < grid.length; i++) {
  for (int j = 0; j < grid[i].length; j++) {
    text(grid[i][j], 
      i*39+40, j*18+40);
  }
}

:wink: