0

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[][]
}
3
  • Do you mean replace an int[] with an int[][], or do you just mean resize an int[]? Commented Nov 9, 2012 at 22:07
  • 2
    You'll have a hard time accomplishing this since int[] and int[][] are stored differently in memory. Could you provide context for why you need this functionality? Perhaps there's a workaround that might suit you better. Commented Nov 9, 2012 at 22:08
  • @TheCapn I am trying to make a simple card game and have the computer play it and find all the outcomes of the game and give the best outcome. each step in the game will be recorded. I want to store all the outcomes in a big array so that i can look through it and pick the best one. problem is, i dont know how many steps I will have to take in the game until it ends, so that is why i thought miltidim. array would work best for me. what do you think? Commented Nov 10, 2012 at 2:17

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.