-1

Some people tell me its the first option, but other people tell me its the second one. Where do the rows and where to de columns actually go? I'd appreciate the help, thanks.

1) Double array[][] = new Double[5][3];

2) Double array[][] = new Double[3][5];

2 Answers2

0

There is no real concept of matrices in Java. What you're referring to is a two-dimensional array, or in other words an array of arrays.

Writing Double[5][3] will create an array of length 5, containing arrays of length 3 and your other example will do the opposite. Therefore the answer to your question depends on how you want to visualise it. The most obvious way for me is to say that each inner array represents a row in the matrix, therefore I would lean towards Double[3][5], then indexing with a row and column would look like array[row][column] which makes a lot of sense.

Henry Twist
  • 4,320
  • 3
  • 12
  • 36
0

This question usually comes down to which convention do you prefer or which one is predominantly used in your field or, more narrowly, programming language.

I found this answer stating that Java is "row major". This is the convention I always follow while working with 2D arrays in Java. Although, Wikipedia article on row- and column-major order refers to the part of Java Language Specification, stating that this langauge is neither row-major nor column-major. Instead, it uses Iliffe vectors to store multi-dimensional arrays, meaning that data in the same row is stored continuously in the memory, but the rows themselves are not. Address of the first element of each row is stored in an array of pointers.

Despite it's impossible to clasify Java memory model as a strictly row- or column-major respective, the usage of Iliffe vectors prompts to perceive it as row-major. Therefore, in order to create a matrix of 3 rows and 5 columns, you should use:

Double array[][] = new Double[3][5];
Maks Babarowski
  • 320
  • 2
  • 8