簡體   English   中英

在java中復制一個二維數組

[英]copy a 2d array in java

我有一個稱為 int 類型的矩陣的二維數組,我想將其復制到方法中的局部變量,以便我可以對其進行編輯

復制數組的最佳方法是什么,我遇到了一些麻煩

例如

    int [][] myInt;
    for(int i = 0; i< matrix.length; i++){
        for (int j = 0; j < matrix[i].length; j++){
            myInt[i][j] = matrix[i][j];
        }
    }

    //do some stuff here
    return true;
}

有兩種復制數組的好方法是使用 clone 和System.arraycopy()

以下是如何將克隆用於 2D 案例:

int [][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
    myInt[i] = matrix[i].clone();

對於 System.arraycopy(),您使用:

int [][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
{
  int[] aMatrix = matrix[i];
  int   aLength = aMatrix.length;
  myInt[i] = new int[aLength];
  System.arraycopy(aMatrix, 0, myInt[i], 0, aLength);
}

that they are faster and less mistake-prone than doing it yourself.我沒有基准,但我可以用我的打賭,它們比自己做更快,更不容易出錯 特別是System.arraycopy()因為它是在本機代碼中實現的。

希望這可以幫助。

編輯:修復了錯誤。

可以在 Java 8 中使用流來復制二維數組。

@Test
public void testCopy2DArray() {
   int[][] data = {{1, 2}, {3, 4}};
   int[][] dataCopy = Arrays.stream(data)
             .map((int[] row) -> row.clone())
             .toArray((int length) -> new int[length][]);

   assertNotSame(data, dataCopy);
   assertNotSame(data[0], dataCopy[0]);
   assertNotSame(data[1], dataCopy[1]);

   dataCopy[0][1] = 5;
   assertEquals(2, data[0][1]);
   assertEquals(5, dataCopy[0][1]);
}

您沒有初始化本地二維數組。

int[][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
{
  myInt[i] = new int[matrix[i].length];
  for (int j = 0; j < matrix[i].length; j++)
  {
    myInt[i][j] = matrix[i][j];
  }
}

如果數據很大,您應該考慮使用合適的線性代數庫,如coltnd4j 如果數組是一維的, System.arraycopy可能只會更快。 否則它無法將整個數據復制為一個單元,然后像在 numpy 或 R 中那樣對其進行整形。

你也可以這樣編碼 myInt = matrix.clone();

暫無
暫無

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

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