≡ Menu

Repost: Rocket Java: Initializing arrays of arrays

From IRC, from whence many “interesting” questions come:

“If I have a 4 dimensional integer array in Java, is there a way to initialise every element in it to a particular value?”

Well. First off, you don’t have a four-dimensional array. You have a one-dimensional array of one dimensional arrays of one dimensional arrays of one dimensional arrays.

Every one of these arrays have their own length; they’re not uniform. Every one of these arrays have their own reference in the heap; they’re not contiguous.

Therefore, we’ve eliminated C-like memset() calls, in one fell swoop. Swoop, us! Swoop! (Swooping is fun.)

The key here is to think about how arrays like that are even initialized: chances are, with lots of loops.

Let’s say you want a 4x4x4x4 array of integers. Here’s code to initialize one of the endpoints to the default values for an array of ints, zero:

int[][][][] myArray=new int[4][][][];
myArray[0]=new int[4][][];
myArray[0][0]=new int[4][];
myArray[0][0][0]=new int[4]; // we will be playing with this line some.

Now, you can always use a different value if you lose the dimension on the last line. Setting all four values to one would look like this:

myArray[0][0][0]=new int[] {1,1,1,1};

That’s not very flexible, though.

The Java API has Arrays.fill(), which works for multiple primitive types (and Object), but the first argument isn’t an array of arrays – it’s a single-dimensional array. There are forms of the method that take ranges, which is nice, but the version linked to there will copy a value to each element in the list. (By the way, Arrays.fill(Object[], Object) seems faintly useless to me – if only that were a closure!)

Therefore, we could replace that last line, again:

myArray[0][0][0]=new int[4];
java.util.Arrays.fill(myArray[0][0][0], 14);

That’s a little better, but not much.

The bottom lines here: Java doesn’t have multidimensional arrays, so there’s not an “optimization” that leverages contiguous memory available. You can always slice your arrays yourself (by creating int[256], for example, and manually indexing, which would definitely give you regular arrays of arrays, which Java does not offer you), but otherwise… no. No multidimensional arrays.

Since there are no multidimensional arrays (and no contiguous arrays), to fill an array of arrays with a single value, you get to loop. Somewhere. Sorry, folks.

Author’s Note: Another repost.

{ 1 comment… add one }

Leave a Comment

%d bloggers like this: