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
.
3 Likes
Chrisir
February 23, 2021, 10:10am
3
// 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);
}
}
is there really no such thing as boolean abc[] = new boolean[9](true)
?
except for ={true,true,true,true,true,...}
1 Like
Well, most we can do in Java is use Arrays .fill() :
docs.Oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#fill(byte[],byte)
final boolean[] abc = new boolean[9];
java.util.Arrays.fill(abc, true);
println(str(abc));
exit();
For your previous 2D array we can shorten its initialization loop using Arrays .fill() this way:
static final int ROWS = 3, COLS = 2, DEFAULT = 123;
final int[][] grid = new int[ROWS][COLS];
{
for (final int[] row : grid) java.util.Arrays.fill(row, DEFAULT);
}
void setup() {
for (final int[] row : grid) println(str(row));
exit();
}
2 Likes
Hi!
Thank you for showing me this!
I just went through several java documentation pages and saw a “0x123a” example. It is supposed to be hex number. Is there any other 0x value or something like 2x010101?
Use prefix 0b
for binary literals: static final int DEFAULT = 0b010101; // 21
are there any others? would 0d100 mean 100 in decimal?
Look for section “Integer Literals” for all available Java prefixes on my 1st posted link:
docs.Oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
However it seems like they’ve skipped the octal number system.
For octal literals just prefix them w/ 0
like this: 0400
= 256
.