[英]Is it possible to define an arbitrarily, highly nested array in Java?
在JavaScript中,我們可以靈活地定義高度嵌套的數組。 例如,以下。
var arr1 = [ [0, 1], [2, 3] ];
var arr2 = [
[ [0, 1], [2, 3] ],
[ [4, 5], [6, 7] ]
];
是否可以在Java中為類的字段定義類似的內容? 該字段必須能夠存儲嵌套數組的任意尺寸/深度。
我正在考慮使用列表列表。
List<List<Integer>> arr = new ArrayList<>();
但是,從某種意義上講,這只是2D矩陣。 請注意,對於我的用例而言,索引是重要的(具有意義)。
我想我也可以創建一個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
}
任何提示表示贊賞。
Java是一種強類型語言,您可以在聲明數組時定義其維數。 喜歡,
int[][] arr1 = { { 0, 1 }, { 2, 3 } };
int[][][] arr2 = { { { 0, 1 }, { 2, 3 } }, { { 4, 5 }, { 6, 7 } } };
System.out.println(Arrays.deepToString(arr2));
但是,也可以使Object
引用任何數組(因為數組是Object
實例)。 在上面的示例中,請注意簽名是Arrays.deepToString(Object[])
。
1)您可以執行以下操作(如果對您而言有意義):
List<List<List<List<Integer>> arr = new ArrayList<>();
2)另外,作為Javascript,Java可以具有多維數組
Integer[][] arr = {{1,2},{2,3}};
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)您也可以使用實現多維數組的庫。 喜歡:
我認為最后一種選擇是您情況下最好的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.