要往Java數(shù)組里添加數(shù)據(jù),需要先創(chuàng)建一個新的數(shù)組,然后將原來的數(shù)組中的數(shù)據(jù)復(fù)制到新的數(shù)組中,并在新的數(shù)組末尾添加新的數(shù)據(jù)。
以下是一個示例代碼:
// 原始數(shù)組
int[] originalArray = {1, 2, 3, 4, 5};
// 新數(shù)組長度比原數(shù)組長度大1,用于添加新數(shù)據(jù)
int newLength = originalArray.length + 1;
int[] newArray = new int[newLength];
// 將原數(shù)組中的數(shù)據(jù)復(fù)制到新數(shù)組中
System.arraycopy(originalArray, 0, newArray, 0, originalArray.length);
// 添加新數(shù)據(jù)到新數(shù)組末尾
int newData = 6;
newArray[newLength - 1] = newData;
// 打印新數(shù)組
System.out.println("新數(shù)組:");
for (int i = 0; i < newLength; i++) {
System.out.println(newArray[i]);
}
執(zhí)行上述代碼后,將會輸出新數(shù)組:1, 2, 3, 4, 5, 6。