簡體   English   中英

如何處理多維數組?

[英]How to handle multidimensional array?

我想將數組存儲在一個數組中,但是我不知道該怎么做。

我想要的是:我有一個名為array的數組。

在一種方法中,我想向該數組追加一個項目,該項目也將是一個數組。

例如,這將在我的第一個數組中:(調用該方法時,它的每一項都會附加)

{1,2},{2,3},{5,6}

謝謝。

要純粹使用數組,請參閱: http : //www.ensta.fr/~diam/java/online/notes-java/data/arrays/arrays-2D-2.html

例如,分配所有您可以做的事情:

int[][] tri;

//... Allocate each part of the two-dimensional array individually.
tri = new int[10][];        // Allocate array of rows
for (int r=0; r < 2; r++) {
    tri[r] = new int[2];  // Allocate a row
}

但是,如果需要支持附加操作,最好使用其他數據結構(如List,ArrayList等)來保存頂級“數組”。 這樣,您可以僅向其添加數組,而不必玩重新分配它的游戲。 肖恩的解決方案非常適合這一點。

void append(List<int[]> arrays) {
  int[] newItem = ...;
  arrays.add(newItem);
}

...

List<int[]> arrays = new ArrayList<int[]>();
...
// then call append() to do your appending
append(arrays);
...
// now get the array of arrays out of it
int[][] as2DArray = arrays.toArray(new int[0][]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM