我正在用 Java 開發一個游戲,我需要快取一些基于位置的資訊。如果我有以下陣列:
int[][] array = {
{1, 2, 3},
{1, 2, 3},
{1, 2, 3}
};
然后我有另一個陣列:
int[][] otherArray = {
{4, 5, 6},
{4, 5, 6},
{4, 5, 6}
};
現在我想以一種特殊的方式將它們結合起來。我想添加otherArray到array. 所以結果應該是這樣的:
int[][] combinedArray = {
{4, 5, 6, 1, 2, 3},
{4, 5, 6, 1, 2, 3},
{4, 5, 6, 1, 2, 3}
};
然后我有另一個組合陣列:
int[][] otherCombinedArray = {
{30, 17, 139, 65, 335, 99},
{50, 43, 57, 53, 423, 534},
{90, 67, 78, 24, 99, 67}
};
現在我想將它添加到原始組合陣列的頂部。所以最終的結果應該是這樣的:
int[][] finalCombinedArray = {
{30, 17, 139, 65, 335, 99},
{50, 43, 57, 53, 423, 534},
{90, 67, 78, 24, 99, 67},
{4, 5, 6, 1, 2, 3},
{4, 5, 6, 1, 2, 3},
{4, 5, 6, 1, 2, 3}
};
有人可以給我指出一個好的圖書館或內置的方法嗎?我還想指出,該方法的計算量不應太大(例如多次回圈遍歷所有陣列,并且不應使用太多記憶體,例如 80MB)。
感謝您的幫助!
uj5u.com熱心網友回復:
Java 本身不提供連接方法,但我們可以使用System.arraycopy(如上面@user16320675 所建議的)
隨著System.arraycopy你指定陣列復制 目標陣列- >你有大小為10,大小為2 B的陣列A,并且使用命令你的B排列復制到A.
int[] source = { 1,2,3,4,5 };
int[] destination = new int[10];
// You can play with the numbers below
int COPY_AT_INDEX = 0; // Start to copy at position destination[0]
int AMOUNT_TO_COPY = 5; // Copying from 0 to source.length
System.arraycopy(source, 0, destination, COPY_AT_INDEX, AMOUNT_TO_COPY);
System.out.println(Arrays.toString(source)); // [1, 2, 3, 4, 5]
System.out.println(Arrays.toString(destination)); // [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
現在,如果我們使用arraycopy, 似乎您必須確定何時復制為行,何時復制為列。
// Assuming a[][] and b[][] have the same size.
public int[][] mergeAsColumns(int[][] a, int[][] b) {
int rows = a.length;
int columns = a[0].length;
int[][] merged = new int[rows][2 * columns];
for (int i = 0; i < a.length; i ) {
System.arraycopy(a[i], 0, merged[i], 0, columns);
System.arraycopy(b[i], 0, merged[i], rows, columns);
}
return merged;
}
Merging as Rows 與另一個類似,但更改了您想要影響的位置以及創建合并陣列的方式。
// Assuming a[][] and b[][] have the same size.
public int[][] mergeAsRows(int[][] a, int[][] b) {
int rows = a.length;
int columns = a[0].length;
int[][] merged = new int[2 * rows][columns];
for (int i = 0; i < rows; i ) {
System.arraycopy(a[i], 0, merged[i], 0, columns);
System.arraycopy(b[i], 0, merged[rows i], 0, columns);
}
return merged;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312875.html
