[英]Partial copy of an array in java
[[-6, 3, 9], [-7, 2, 9], [-3, 2, 5], ... , [3, 4, 1]]
我正在使用的數組的結構類似於上面的數組。
我的目標是根據先前確定的特定位置划分此數組。
我已經嘗試過Arrays.copyOf
, Arrays.copyOfRange
和System.arraycopy
,但是沒有取得成功,這就是為什么我為此編寫了自己的方法的原因; 它也沒有用。
partitionResult
是一個int
類型的實例(變量)數組,其結構類似於arrayOfVals
盡管我只打算復制一部分,但arrayOfVals
似乎已用整個partitionResult
數組初始化。 我已經測試了System.out.println (partitionResult[begin+i][j])
,並且打印的值是所需的。
private int[][] copyArray(int begin, int end)
{
int SUBARRAY_SIZE = 2;
// below the '+1' is due to zero-indexing
int[][] arrayOfVals = new int[end-begin+1][SUBARRAY_SIZE+1];
end -= begin;
for (int i = 0; i <= end; i++) {
for (int j = 0; j <= SUBARRAY_SIZE; j++) {
arrayOfVals[begin][j] = partitionResult[begin+i][j];
}
}
return arrayOfVals;
}
為什么我不能按要求執行以下操作?
private void foo(int begin)
{
int[][] arrayOne = copyArray(0, begin);
int[][] arrayTwo = copyArray(begin+1, partitionResult.length -1);
...
}
編輯:
[[-6, 3, 9], [-7, 2, 9], [-3, 2, 5], [3, 4, 1], [0, 5, 5], [2, 3, 1], [3, 4, 1]]
這是我的測試數組。 我想在begin
位置使用copyArray
方法拆分此數組。
當我打印要復制的值partitionResult[begin+i][j]
,結果與應有的結果完全相同。 但是,顯示最終的arrayOfVals
輸出不是我打印的內容,而是整個partitionResult
數組。
我想要arrayOne
等於[[-6, 3, 9], [-7, 2, 9], [-3, 2, 5]]
arrayOne
[[-6, 3, 9], [-7, 2, 9], [-3, 2, 5]]
arrayOne
[[-6, 3, 9], [-7, 2, 9], [-3, 2, 5]]
arrayOne
[[-6, 3, 9], [-7, 2, 9], [-3, 2, 5]]
和arrayTwo
等於[[3, 4, 1], [0, 5, 5], [2, 3, 1], [3, 4, 1]]
arrayTwo
[[3, 4, 1], [0, 5, 5], [2, 3, 1], [3, 4, 1]]
arrayTwo
[[3, 4, 1], [0, 5, 5], [2, 3, 1], [3, 4, 1]]
arrayTwo
[[3, 4, 1], [0, 5, 5], [2, 3, 1], [3, 4, 1]]
arrayTwo
[[3, 4, 1], [0, 5, 5], [2, 3, 1], [3, 4, 1]]
Edit2:問題不在於方法copyArray
而copyArray
另一個方法。 我編寫的toString
方法顯示的是實例變量partitionResult
所使用的值,而不是我傳遞給它的數組-這使得好像沒有任何內容被復制。 這個錯誤對我來說應該是顯而易見的。 我非常感謝您的建議。
但是,@ Andrea發現了一個小錯誤。
錯誤應該在
arrayOfVals[begin][j] = partitionResult[begin+i][j];
更改為
arrayOfVals[i][j] = partitionResult[begin+i][j];
因為您新創建的數組必須從0開始插入值。
這應該足夠簡單,您只是通過更改end
來使自己變得困難,從而使您難以理解循環的進程。 只需復制begin
和end
(包括)之間的值,但請確保克隆每個子數組。 (克隆有效地替換了您的內部循環。)
private int[][] copyArray(int begin, int end) {
// Calculate the size of the output
// below the '+1' is due to zero-indexing
int size = end - begin + 1;
int[][] arrayOfVals = new int[size][];
for (int i = 0; i < size; i++) {
// Clone each subarray to make sure changes to the copy
// don't affect the internal array
// (A shallow .clone() suffices for integer arrays)
arrayOfVals[i] = partitionResult[begin + i].clone();
}
return arrayOfVals;
}
這將在調用foo(2)
時為您的示例輸入提供預期的輸出。
如果fromArray是輸入數組,而index是要中斷輸入數組的索引,則可以執行以下操作:
System.arraycopy(fromArray, 0, arrayOne, 0, index);
System.arraycopy(fromArray, index+1, arrayTwo, 0, fromArray.length-index);
創建二維數組時,您擁有的是數組數組。 看這樣的問題:
[0,0] [1,0] [2,0] ... [n,0]
[0,1] [1,1] [2,1] ... [n,1]
[0,2] [1,2] [2,2] ... [n,2]
[[-6、3、9],[-7、2、9],[-3、2、5],...,[3、4、1]]
我們可以如下表示您的示例數據集:
[-6] [-7] [-3] ... [ 3]
[ 3] [ 2] [ 2] ... [ 4]
[ 9] [ 9] [ 5] ... [ 1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.