2

if new int[5] creates an int array of length 5, and new String[5] creates a String array of length 5,

then by that logic, shouldn't new int[3][4] create an int[3] array of length 4 like {{1,2,3}, {1,2,3}, {1,2,3}, {1,2,3}}?

Lul
  • 21
  • 1
  • You mean three arrays, each of length four? Also, the default values are `0`. – Elliott Frisch May 01 '17 at 01:17
  • 2
    As far as I know, in all programming languages, for a two dimensional array, first index represents length of the array and the second index represents length of each sub-array – Sherin Binu May 01 '17 at 01:19
  • So it will only create three array of length four instead four array of length three – Sherin Binu May 01 '17 at 01:20
  • 1
    I believe he's asking why `arr[j][k]` creates `j` arrays of length `k` instead of `k` arrays of length `j`. Why isn't `arr[j][k`] equal to `(arr[j])[k]`? Why the switch to a row-column implementation when column-row seems more intuitive in the context of the language? – phasma May 01 '17 at 02:50

1 Answers1

0

As phasma said, this question seems to be asking why java switches to 'column-major' during array creation and back to 'row-major' for access. It seems like multidimensional arrays in Java are allocated using a reversed intuition, but then are accessed using the 'correct' intuition.

An int[][] should mean an array of arrays of int, right? And it does! So when creating an array, you might be thinking like this: int[][] arr = new (int[3])[4]. Because it should be an array of size 4 containing arrays of size 3!

However, if you were to use this intuition, you would then have to access the array like this: (arr[0-3])[0-2] instead of (arr[0-2])[0-3] like you had created the array, and the order would be switched and would be more confusing and hard to debug.

I believe that the reason most languages do this is to keep things consistent and to prevent confusion. You are smart to think this way, since most people would never notice.

name
  • 362
  • 2
  • 12