83

When creating a 2D array, how does one remember whether rows or columns are specified first?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Matt B
  • 1,653
  • 2
  • 15
  • 20

9 Answers9

94

Java is considered "row major", meaning that it does rows first. This is because a 2D array is an "array of arrays".

For example:

int[ ][ ] a = new int[2][4];  // Two rows and four columns.

a[0][0] a[0][1] a[0][2] a[0][3]

a[1][0] a[1][1] a[1][2] a[1][3]

It can also be visualized more like this:

a[0] ->  [0] [1] [2] [3]
a[1] ->  [0] [1] [2] [3]

The second illustration shows the "array of arrays" aspect. The first array contains {a[0] and a[1]}, and each of those is an array containing four elements, {[0][1][2][3]}.

TL;DR summary:

Array[number of arrays][how many elements in each of those arrays]

For more explanations, see also Arrays - 2-dimensional.

MrHappyAsthma
  • 5,675
  • 8
  • 45
  • 76
  • 8
    I enjoyed the visualization provided in this answer. – Donato Jun 13 '15 at 17:35
  • 1
    I'm not persuaded that either this answer or its source material convincingly demonstrates that rows should be the first number. I don't see a reason we can't do columns first and then rows. And if it's a convention, I don't see anything here that strongly establishes that. – Mathieu K. May 14 '19 at 22:17
  • 1
    The OP did not ask for the reason "why" Java is row major (which it technically isn't, but is easiest to conceptualize around if you imagine that it is and worry less about the memory lay out). But rather asked "how does one remember" to conceptually specify rows first. I find visualization to be the best way to remember. It should be noted that Java doesn't *really* use row major per se, but really specifies arrays-of-arrays as I touch on briefly in my answer. A really good visualization of explanation of how its laid out can be found here: https://stackoverflow.com/a/6631081/1366973 – MrHappyAsthma May 14 '19 at 22:24
21

While Matt B's may be true in one sense, it may help to think of Java multidimensional array without thinking about geometeric matrices at all. Java multi-dim arrays are simply arrays of arrays, and each element of the first-"dimension" can be of different size from the other elements, or in fact can actually store a null "sub"-array. See comments under this question

Community
  • 1
  • 1
Kevin Welker
  • 7,211
  • 1
  • 33
  • 53
  • 5
    +1 for expressing contrast of ARRAY vs MATRIX! Arrays have no geometric definition. If you think a 1D array is vertical then row is first, if you think a 1D array is horizontal then col is first. When using a rectangular 2D array there is no logical distinction, as long as you keep it the same throughout your code. IMPLEMENT ACCORDING TO YOUR USAGE! (don't make yourself traverse the first element of each subarray when you could just traverse the first subarray) – Ron Feb 21 '14 at 05:45
16

Instinctively one thinks geometrically: horizontal (X) axis and then vertical (Y) axis. This is not, however, the case with a 2D array, rows come first and then columns.

Consider the following analogy: in geometry one walks to the ladder (X axis) and climbs it (Y axis). Conversely, in Java one descends the ladder (rows) and walks away (columns).

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Matt B
  • 1,653
  • 2
  • 15
  • 20
  • 12
    @Luiggi Please refer to [It's OK to Ask and Answer your Own Question](http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/) In which you will find (among other things): `To be crystal clear, it is not merely OK to ask and answer your own question, it is explicitly encouraged.` – Matt B Jul 25 '12 at 02:58
  • 1
    That applies to questions like [this one](http://stackoverflow.com/q/2793150/1065197) or [this good question](http://stackoverflow.com/q/247621/1065197). Also, see that both questions are community wiki (the votes doesn't add reputation to these people), they have a good explanation and are done to help people, not to get benefit for themselves. – Luiggi Mendoza Jul 25 '12 at 03:03
  • @Zéychin This would probably be more appropriate in chat. – Matt B Jul 25 '12 at 03:06
  • It is OK to imagine the transpose. i.e., if you imagine that columns come first then rows it is really O.K. . and this is common in matrix operations algorithms written in Java . – Muhammad Annaqeeb Oct 29 '13 at 01:24
  • Unfortunately, there is no standard. When people talk about computer screens, they say "width by height," e.g., 1024x768 or 1440x900. But when people talk about recipe cards, they say, "3x5 card." – Dave Burton Sep 13 '16 at 11:58
5

All depends on your visualization of the array. Rows and Columns are properties of visualization (probably in your imagination) of the array, not the array itself.

It's exactly the same as asking is number "5" red or green?

I could draw it red, I could draw it greed right? Color is not an integral property of a number. In the same way representing 2D array as a grid of rows and columns is not necessary for existence of this array.

2D array has just first dimention and second dimention, everything related to visualizing those is purely your flavour.

When I have char array char[80][25], I may like to print it on console rotated so that I have 25 rows of 80 characters that fits the screen without scroll.

I'll try to provide viable example when representing 2D array as rows and columns doesn't make sense at all: Let's say I need an array of 1 000 000 000 integers. My machine has 8GB of RAM, so I have enough memory for this, but if you try executing var a = new int[1000000000], you'll most likely get OutOfMemory exception. That's because of memory fragmentation - there is no consecutive block of memory of this size. Instead you you can create 2D array 10 000 x 100 000 with your values. Logically it is 1D array, so you'd like to draw and imagine it as a single sequence of values, but due to technical implementation it is 2D.

Sasha
  • 7,731
  • 4
  • 41
  • 72
  • Interesting point! I never thought of how an array of arrays would use memory fragmentation. To further drive it home, the first number would represent the number of pointers, and the second number represents the length of the array pointed to by each pointer (which also means the 2D version of the 1D array actually allocates MORE memory for the sake of those pointers). – 4castle May 18 '16 at 03:08
  • @4castle, you are right, jagged array will use slightly more memory than equivalent fixed size 2D array, but sometimes it may save you from OutOfMemory exception surprisingly. I think it's because of .NET trying to allocate big objects using consecutive memory blocks (not sure why virtual memory blocks mapping doesn't solve the problem). I'm not an expert in .NET memory model though, so don't take it as a fact. – Sasha May 18 '16 at 09:23
  • .NET? This was a Java question. Does the Windows JVM use .NET? – 4castle May 18 '16 at 22:57
  • @4castle, Sorry, I forgot already it's Java question, but I'm pretty sure there is not much differences in .NET and JVM in terms of representing jagged and simple 1-dimentional arrays in memory. – Sasha May 19 '16 at 09:38
2

In Java, there are no multi-dimension arrays. There are arrays of arrays. So:

int[][] array = new int[2][3];

It actually consists of two arrays, each has three elements.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Eng.Fouad
  • 107,075
  • 62
  • 298
  • 390
1

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.

Lord Luce
  • 33
  • 7
0

In java the rows are done first, because a 2 dimension array is considered two separate arrays. Starts with the first row 1 dimension array.

Nour Lababidi
  • 386
  • 3
  • 7
  • 1
    This is in C# not Java. In the Java programming language, a multidimensional array is an array whose components are themselves arrays. So each component arrays may have a different length. This notation you are writing is in C#, which force rectangular 2D array - which java do not have - which is equivalent to forcing all component arrays to have equal length. – Muhammad Annaqeeb Oct 08 '13 at 20:27
  • Thank You :) Muhammad Annaqeeb – Nour Lababidi Jun 11 '14 at 03:45
  • Thank You, I didn't know the part about the rectangular 2D array part. That's helpful answer. – Nour Lababidi Jul 29 '15 at 17:39
  • I've updated my answer to more detailed and correct answer. Thank You, – Nour Lababidi Dec 31 '15 at 20:09
0

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.

spencemw
  • 81
  • 2
  • 10
0

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.

Our Man in Bananas
  • 5,467
  • 19
  • 82
  • 136
Salem
  • 1