如何创建任意深度的Java中的嵌套数组? [英] How to create a nested array of arbitrary depth in java?
问题描述
我想创建数组等数组的数组...,但我不知道深,它需要多少嵌套级别要到运行时。
I am trying to create an array of arrays of arrays etc..., except I don't know how many nested levels deep it needs to be until runtime.
根据输入,我可能需要为 INT []
, INT [] []
, INT [] [] [] [] [] []
,或其他任何东西。 (对于背景下,我想构造一个 N维网作为一个细胞自动机,其中N是作为参数传递。)
Depending on the input, I might need either int[]
, int[][]
, int[][][][][][]
, or anything else. (For context, I am trying to construct an N-dimensional grid for a cellular automaton, where N is passed as a parameter.)
我没有任何code你,因为我不知道如何去这一点;我怀疑是根本不可能只使用数组。任何帮助,或者替代性解决方案,将AP preciated。
I don't have any code for you because I have no idea how to go about this; I suspect is not possible at all using just arrays. Any help, or alternative solutions, would be appreciated.
推荐答案
您可以用一个Object []做到这一点,限制其成员任一对象[]或INT []。
You could do this with an Object[], limiting its members to either Object[] or int[].
例如,下面是在另一个深藏在三个级别中的一部分,以及两个深层次的数组:
For example, here's an array that goes three levels deep in one part, and two levels deep in another:
Object[] myarray = new Object[] {
new Object[] { new int[] { 1, 2 },
new int[] { 3, 4 }},
new int[] { 5, 6 }
};
您已经创建了它之后,你可能会想访问的成员。在你的情况,你知道精度N前面,所以你知道在什么深度,期待一个Object []和在什么深度,期待一个int []。
After you've created it, you may want to access members. In your case, you know the depth N up front, so you know at what depth to expect an Object[] and at what depth to expect an int[].
不过,如果你不知道深浅,你可以使用的反射的确定成员是否是另一个对象[]级别或叶INT []。
However, if you didn't know the depth, you could use reflection to determine whether a member is another Object[] level or a leaf int[].
if ( myarray[0] instanceof Object[] ) {
System.out.println("This should print true.");
}
编辑:
下面是一个草图[未经考验到目前为止,对不起]访问已知深度的数组成员的方法,给定指数的数组。该m_root成员可以是一个Object []或int []。 (你可以进一步放宽此支持标量)。
Here's a sketch [untested so far, sorry] of a method that access a member of an array of known depth, given an array of indices. The m_root member can be an Object[] or an int[]. (You could relax this further to support scalars.)
public class Grid {
private int m_depth;
private Object m_root;
...
public int get( int ... indices ) {
assert( indices.length == m_depth );
Object level = m_root;
for ( int i = 0; i + 1 < m_depth; ++i ) {
level = ((Object[]) level)[ indices[i] ];
}
int[] row = (int[]) level;
return row[ indices[m_depth - 1] ];
}
}
这篇关于如何创建任意深度的Java中的嵌套数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!