Semur Nabiev
Semur Nabiev

Reputation: 800

java increase dimension in array

Is it possible (i am sure it is) and not too complicated to make dynamic multidimensional arrays which would increase dimension if needed?

// Array[] 1 has 2 dimensions
if(blah=blah)
{
   Array[] 1 gets second dimension and is now Array[][]
}

Upvotes: 0

Views: 225

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

No, it is not possible: the number of dimensions ofn an array is a property of the array's type, not of the array object, so you cannot do this with built-in Java arrays.

In order to emulate an array that can change the number of dimensions at runtime you would need to build your own class. You can base that class on an array or an ArrayList, but there would be one limitation: you would not be able to use subscript operators on your emulated array.

There is also the "ugly" solution: you can store your array without a type - essentially, as a typeless Object. You can assign arrays with any number of dimension to a variable of type Object, like this:

Object a = new int[10];
a = new int[10][2];
a = new int[10][2][5];

The catch is that you cannot access elements of such array without performing a cast:

a[2][1][0] = 7; // Will not compile

This will compile and work, but the construct is rather unreadable:

((int[][][])a)[2][1][0] = 7;

Also note that the prior content of the array will be lost on reassignment, unless you make a copy of it.

Upvotes: 5

Related Questions