1

I am new to Java and I saw a video about 2D arrays online. But what about 3D arrays?

Is it possible to make a 3D array in Java? If so, how can this be done. Also, would using 3 separate 1D arrays (that are linked together) be equivalent to using 1 3D array? Finally, what is the efficiency of traversing through a 3D array?

  • 2
    Possible duplicate of [Java N-Dimensional Arrays](http://stackoverflow.com/questions/4770926/java-n-dimensional-arrays) – Andreas Fester Jul 26 '16 at 13:32
  • 1
    No, three 1D arrays are not the same as one 3D array. – Andreas Fester Jul 26 '16 at 13:32
  • 4
    A 3D array of primitive integers: `int[][][] array;` Whether you should be using a single 3D array, 3 x 1D arrays, or possible another data structure totally depends on the type of problem you are solving. – Tim Biegeleisen Jul 26 '16 at 13:33
  • 1
    Have no idea why OP would think 3 1D array is equivalent to 1 3D array. Just use an example, a 3D array, of 10-element in each dimension, gives you totally 10x10x10 = 1000 elements. 3 1D 10-element array gives you 30 elements. Obviously different – Adrian Shum Jul 27 '16 at 02:35

1 Answers1

1

Making a 3D array is quite possible in Java. It's as simple as declaring the type T[][][] array;. Three separate 1D arrays are not equivalent to one 3D array. You would need n 2D arrays to be equivalent to one 3D array. The efficiency of traversing a 3D array is practically O(n³).

kamoroso94
  • 1,713
  • 1
  • 16
  • 19
  • So, for those who were sleeping through algebra/trig/whatever, is `O(n³)` a good thing? And as Tim mentioned in a comment, wouldn't what you are trying to do affect the design? – Mark Stewart Jul 27 '16 at 02:51
  • 1
    Well O(n³) means the time it takes to traverse an n×n×n 3D array is proportional to n³. So for instance, traversing a 1×1×1 3D array would require 1 iteration, whereas traversing a 2×2×2 array would require 8 iterations. But as Tim mentioned, depending on what you're doing, a 3D array may not be the best data structure for solving your problem. – kamoroso94 Jul 27 '16 at 02:59