When creating a 2D array, how does one remember whether rows or columns are specified first?
In c++ (distant, dusty memory) I think it was a little easier to look at the code and understand arrays than it is in Java sometimes. Both are row major. This illustration worked for me in helping to understand.
Given this code for a 2d array of strings...
String[][] messages;
messages = new String[][] {
{"CAT","DOG","YIN","BLACK","HIGH","DAY"},
{"kitten","puppy","yang","white","low","night"}
};
int row = messages.length;
int col = messages[0].length;
Naming my ints as if it were a 2d array (row, col) we see the values.
row = (int) 2
col = (int) 6
The last two lines of code, where we try to determine size and set them to row and col does not look all that intuitive and its not necessarily right.
What youre really dealing with here is this (note new variable names to illustrate):
int numOfArraysIn = messages.length;
int numOfElementsIn0 = messages[0].length;
int numOfElementsIn1 = messages[1].length;
Where messages.length tells you messages holds two arrays. An array of arrays.
AND then messages[x].length yields the size of each of the individual arrays 0 1 inside messages.
numOfArraysIn = (int) 2
numOfElementsIn0 = (int) 6
numOfElementsIn1 = (int) 6
When we print with a for each loop....
for (String str : messages[0])
System.out.print(str);
for (String str : messages[1])
System.out.print(str);
CATDOGYINBLACKHIGHDAYkittenpuppyyangwhitelownight
Trying to drop the brackets and print like this gives an error
for (String str : messages)
System.out.print(str);
incompatible types: String[] cannot be converted to String
The above is important to understand while setting up loops that use .length to limit the step thru the array.