Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java N-Dimensional Arrays

I need to be able to have an n-dimensional field where n is based on an input to the constructor. But I'm not even sure if that's possible. Is it?

like image 605
skeggse Avatar asked Jan 22 '11 22:01

skeggse


1 Answers

Here's a nice article that explains how to use reflection to create arrays at run-time: Java Reflection: Arrays. That article explains how to create a one-dimensional array, but java.lang.reflect.Array also contains another newInstance method to create multi-dimensional arrays. For example:

int[] dimensions = { 10, 10, 10 }; // 3-dimensional array, 10 elements per dimension
Object myArray = Array.newInstance(String.class, dimensions); // 3D array of strings

Since the number of dimensions is not known until runtime, you can only handle the array as an Object and you must use the get and set methods of the Array class to manipulate the elements of the array.

like image 170
casablanca Avatar answered Oct 13 '22 13:10

casablanca