[英]How to copy values from a 2d array to a new and bigger one in Java?
如何將二維數組復制到一個新的更大的數組中,以便在新數組中添加更多項目,同時仍然擁有原始數據? 我的代碼越界失敗 - 我的錯誤是什么? 我試着說復制數組應該是原始的array.length + x - 但不起作用。
導入 java.util.Scanner; // 將掃描儀導入程序
公共 class TestTest {
// Declaring Scanner object.
public static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
// Variables
int number = 1;
// Declaring 2d Array
int[][] myArray = new int [3][3];
// Loop values into the array
for(int i =0; i<myArray.length; i++)
{
myArray[i][0]= number;
number++;
myArray[i][1]= (int) (Math.random () * 10) +1;
myArray[i][2]= (int)(Math.random() * ((1000 - 100) + 1)) + 100;
}
// Print the original array
System.out.println("This is original array:");
for(int i =0; i<myArray.length; i++)
{
System.out.println(myArray[i][0]+" " + myArray[i][1]+" "+ myArray[i][2]);
}
// Make a copy of the original array and expand the length with 3.
int[][] copyArray =new int[myArray.length+3][3];
for (int i = 0; i < copyArray.length; ++i)
{
copyArray[i] = new int[myArray[i].length];
for (int j = 0; j < copyArray[i].length; ++j)
{
copyArray[i][j] = myArray[i][j];
}
}
// Print the copy
System.out.println("This is the copy:");
for (int i = 0; i < copyArray.length+3; ++i)
{
System.out.println(copyArray[i][0]+" " + copyArray[i][1]+" "+ copyArray[i][2] );
}
}
}
你得到ArrayIndexOutOfBounds
因為數組copyArray
的長度大於你的源數組myArray
。
因此,當索引i
超過源數組的長度時,此行會導致異常:
copyArray[i] = new int[myArray[i].length];
因為myArray[i]
不會引用嵌套數組。
像這樣試試
int[][] copyArray =new int[myArray.length+3][3];
for (int i = 0; i < myArray.length; ++i) { // length of myArray
copyArray[i] = new int[myArray[0].length]; // 0 instead of i
for (int j = 0; j < myArray[i].length; ++j) { // length of myArray
copyArray[i][j] = myArray[i][j];
}
}
此外,由於 copyArray 已經增加了大小,因此您不需要最后一個 for 循環中的+3 。 希望我有所幫助,祝你好運
請注意,當您在int[][] copyArray = new int[myArray.length+3][3]
中聲明兩個維度時,JVM 會預先分配這些 arrays:- 一個是new int[myArray.length+3][]
plus該int[][]
的每一行都有一個new int[3]
] 。
使用以下代碼查看此內容:
int[][] copyArray =new int[myArray.length+3][3];
System.out.println("copy:"+Arrays.deepToString(copyArray));
// Prints:
// copy:[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
因此,您的for
循環copyArray[i] = new int[myArray[i].length]
中的行是完全沒有必要的 - 它用另一個數組替換了那些新構建的 arrays 。 刪除第二個維度值3
或刪除分配。
但是有更好的方法來復制 arrays,只需調用適用於基本類型或對象的 arrays 的System.arraycopy 。 使用System.arraycopy
的解決方案是:
int[][] copyArray = new int[myArray.length+3][3];
for (int i = 0; i < myArray.length; ++i) {
System.arraycopy(myArray[i], 0, copyArray[i], 0, myArray.length);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.