[英]Is it possible to define an arbitrarily, highly nested array in Java?
In JavaScript, we can flexibly define arbitrarily, highly nested arrays. 在JavaScript中,我们可以灵活地定义高度嵌套的数组。 For example, the following.
例如,以下。
var arr1 = [ [0, 1], [2, 3] ];
var arr2 = [
[ [0, 1], [2, 3] ],
[ [4, 5], [6, 7] ]
];
Is it possible to define something like this in Java for a field of a class? 是否可以在Java中为类的字段定义类似的内容? The field must be able to store arbitrary dimensions/depths of nested arrays.
该字段必须能够存储嵌套数组的任意尺寸/深度。
I was thinking about using a List of Lists. 我正在考虑使用列表列表。
List<List<Integer>> arr = new ArrayList<>();
However, this is in some sense, only a 2D matrix. 但是,从某种意义上讲,这只是2D矩阵。 Note that the index is significant (it has meaning) for my use case.
请注意,对于我的用例而言,索引是重要的(具有意义)。
I suppose I can also create a Tree structure, but that might require some non-trivial work to get it right. 我想我也可以创建一个Tree结构,但这可能需要一些不平凡的工作才能正确完成。
public class Node {
int index; //like the index of an array i want, unique amongst nodes of same level sharing a common parent
List<Integer> values; //the actual elements, if any
List<Node> children; //nesting deeper
}
Any tips are appreciated. 任何提示表示赞赏。
Java is a strongly typed language, you define the dimensionality of the array when you declare it. Java是一种强类型语言,您可以在声明数组时定义其维数。 Like,
喜欢,
int[][] arr1 = { { 0, 1 }, { 2, 3 } };
int[][][] arr2 = { { { 0, 1 }, { 2, 3 } }, { { 4, 5 }, { 6, 7 } } };
System.out.println(Arrays.deepToString(arr2));
However, it is also possible to make an Object
refer to any array (because arrays are Object
instances). 但是,也可以使
Object
引用任何数组(因为数组是Object
实例)。 In the example above, note the signature is Arrays.deepToString(Object[])
. 在上面的示例中,请注意签名是
Arrays.deepToString(Object[])
。
1) You can do something like this (if it makes sense for you): 1)您可以执行以下操作(如果对您而言有意义):
List<List<List<List<Integer>> arr = new ArrayList<>();
2) Also as Javascript, Java can have multi dimensional arrays 2)另外,作为Javascript,Java可以具有多维数组
Integer[][] arr = {{1,2},{2,3}};
3) To create an Array in runtime, you can use reflection: 3)要在运行时创建数组,可以使用反射:
Integer[] array = (Integer[])Array.newInstance(Integer.class, d1);
Integer[][] array = (Integer[][])Array.newInstance(Integer.class, d1, d2);
Integer[][][] array = (Integer[][][])Array.newInstance(Integer.class, d1, d2, d3);
4) Also you can use a library that implements multi dimensional array. 4)您也可以使用实现多维数组的库。 Like:
喜欢:
I think the last option is the best one in your case. 我认为最后一种选择是您情况下最好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.