When creating a 2D array, how does one remember whether rows or columns are specified first?
When creating a 2D array, how does one remember whether rows or columns are specified first?
The best way to remember if rows or columns come first would be writing a comment and mentioning it.
Java does not store a 2D Array as a table with specified rows and columns, it stores it as an array of arrays, like many other answers explain. So you can decide, if the first or second dimension is your row. You just have to read the array depending on that.
So, since I get confused by this all the time myself, I always write a comment that tells me, which dimension of the 2d Array is my row, and which is my column.
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.
In TStringGrid cells property Col come first.
Property Cells[ACol, ARow: Integer]: string read GetCells write SetCells;
So the assignment StringGrid1.cells[2, 1] := 'abcde'; the value is displayed in the third column second row.