PDA

View Full Version : Multi-dimensional Arrays


flux00
10-29-2006, 04:57 PM
I'm working on this n-dimensional array class in Java, wherein the data is actually stored in a one-dimensional array, and when data is accessed the indices are added to the length of the array in that particular dimension. So I've been wondering about the efficiency of this (because you'd have to do 2 additions for a 3-dimensional array) and whether or not standard multi-dimensional arrays have to do the same thing, because memory is linear even if the array is not.

Basically what I'm asking whether or not operations like addition are done 'under the hood' to get the indices linear.


int[][] x = new int[5][5];
x[2][3] = 1;


When accessing x[2][3] would it add 2, 5, and 3 and return what's in the memory there?


package util;
public final class NArray extends Object
{
public final float[] X;
public final int[] dimension;
public NArray(int[] d)
{
super();
dimension = d;
int n=1;
for (int i=0; i<dimension.length; ++i)
{
n*=dimension[i];
}
X = new float[n];
}
public NArray(int n, int d)
{
super();
dimension = new int[n];
int s = 1;
for (int i=0; i<dimension.length; ++i)
{
dimension[i] = d;
s *= d;
}
X = new float[s];
}
public void store(float f, int[] i)
{
if (i.length != dimension.length)
{
return;
}
int r = 0;
for (int i0=1; i0<i.length; ++i0)
{
r += dimension[i0-1]+i[i0];
}
X[r] = f;
}
public float load(int[] i)
{
if (i.length != dimension.length)
{
return Float.NaN;
}
int r = 0;
for (int i0=1; i0<i.length; ++i0)
{
r += dimension[i0-1]+i[i0];
}
return X[r];
}
}

.oisyn
10-29-2006, 05:26 PM
Basically what I'm asking whether or not operations like addition are done 'under the hood' to get the indices linear.

No, because this is allowed:
int[][] x = new int[5][5];
x[3] = new int[10];
If that is allowed, what you're saying can't be possible :)

flux00
10-29-2006, 05:37 PM
Oh, true. I didn't consider that.:happy:

You wouldn't happen to know multi-dimensional arrays are allocated would you?

Reedbeta
10-30-2006, 01:35 PM
Hmm, interesting .oisyn. I always thought that multidimensional arrays were just laid out in row major order. But I guess when you do something like that, it allocates an array of pointers to one-dimensional arrays?

.oisyn
10-30-2006, 02:54 PM
Keep in mind this is a Java topic, Reedbeta ;)

Reedbeta
10-30-2006, 03:16 PM
Oh! I failed to notice that. Makes much more sense now. ;)

SamuraiCrow
10-31-2006, 12:49 PM
You wouldn't happen to know multi-dimensional arrays are allocated would you?

A two dimensional array in Java is an array of one-dimensional arrays. The definitions are recursive also: A 3d array is an array of 2d arrays.

The only reason it's possible to do what .oisyn was saying is becuase one of the arrays in the outer array gets garbage collected when you allocate a new inner array in it.