Alex Dukhan
Alex Dukhan

Reputation: 61

Changing the number of dimensions an Java array has

Is there a way of changing the number of dimensions an array has, i.e making this

int[][] i = new int[3][3];

but using it like this

getArray(i); //where getArray only accepts one dimensional arrays

?

Upvotes: 0

Views: 92

Answers (2)

Stephen C
Stephen C

Reputation: 718906

You cannot change the number of dimensions in a Java array or array type.

But you can make use of the fact that a Java array is an object ... and subtyping .. and declare a getArray method like this:

 Object getArray(Object[], ...) { .... }

You can call this method on a int[][] instance, but a runtime typecast is needed to cast the result to an int[].

For example:

Object getArray(Object[] array, int i) { return array[i]; }

int[][] big = new int[3][3];
int[] slice = (int[]) getArray(big, 0);

On the other hand, if you are really asking about how to flatten a multi-dimensional array into a 1-D array, the getArray method needs to allocate a new array, fill it from the original and return it.

Note you would be returning a brand new array that is unconnected to the original one. And copying an N x N .... x N array is expensive.

For more details: Flatten nested arrays in java

Upvotes: 1

John McClane
John McClane

Reputation: 3568

Java is statically-typed language. This means that you cannot change a variable's type at runtime. But in this particular case you can simply use the following invocation:

getArray(i[2]); // put anything between 0 and (outerArrayLength-1) instead of 2 here

Upvotes: 0

Related Questions