Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Looks like what you are looking for is for some way to declare how many dimensions an array has at runtime. I don't know how this could be done using a multidimensional ArrayList, or any multidimensional structure where you have to specify the dimensionality at compile time.</p> <p>The only answer I see is to use a simple linear array wrapped in a class that converts multidimensional coordinate to and from the its position in the underlying array. This is basically how languages such as C stores multidimensional arrays by using one contiguous chunk of memory.</p> <p>The code would look something like this:</p> <pre><code>import java.util.*; class MultiArray&lt;T&gt;{ private int[] dimensions; private Object[] array; public MultiArray(int ... dimensions){ this.dimensions=dimensions; //Utils.product returns the product of the ints in an array array=new Object[Utils.product(dimensions)]; } public void set(T value, int ... coords){ int pos=computePos(coords); array[pos]=value; } public T get(int ... coords){ int pos=computePos(coords); return (T)(array[pos]); } private int computePos(int[] coords){ int pos=0; int factor=1; for (int i=0;i&lt;coords.length;i++){ pos+=factor*coords[i]; factor*=dimensions[i]; } return pos; } } class Main{ public static void main(String args[]){ MultiArray&lt;Integer&gt; m=new MultiArray&lt;Integer&gt;(new int[]{5,4,3}); Random r=new Random(); for(int i=0;i&lt;5;i++) for(int j=0;j&lt;4;j++) for(int k=0;k&lt;3;k++) m.set(r.nextInt(),i,j,k); for(int i=0;i&lt;5;i++){ for(int j=0;j&lt;4;j++){ for(int k=0;k&lt;3;k++) System.out.print(m.get(i,j,k)+" "); System.out.println(""); } System.out.println("\n"); } } } class Utils{ public static int product(int...a){ int ret=1; for (int x:a) ret*=x; return ret; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload