我正在尝试通过将每个方法调用的数组大小加 1 来调整数组的大小。
我创建了一个静态方法,它以数组作为参数。
public static void addArray(int arrayName[]) {
int tempNum[] = new int[arrayName.length]; // save the numbers before add array size
for (int i = 0; i < arrayName.length; i++) { // because by adding/removing array size, it would clear element array
tempNum[i] = arrayName[i];
}
arrayName = new int[arrayName.length + 1]; // adds array size by 1
for (int i = 0; i < arrayName.length - 1; i++) { // sets all the saved numbers to the new element in the array
arrayName[i] = tempNum[i]; // stops at (length - 1) because I want to leave it blank at the last element
}
}
(对不起,如果代码搞砸了,我不知道如何在此处正确发布代码)
总的来说,我这样做;
public static void main(String[] args) {
int num[] = {0, 1, 2, 3, 4};
addArray(num);
System.out.println(num.length);
}
如您所见,默认数组大小(长度)应为 5,但无论我调用该方法多少次,它始终打印为 5。
现在我开始认为静态方法不允许来自 main 的数组要调整大小?
如果不能,您是否有另一种方法来专门使用静态方法来调整数组的大小?