I am trying to resize an array by adding the array size by 1 per method invoke.
I have created a static method and it takes array as its argument.
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
}
}
(sorry if the code is messed up, I don't know how to properly post code in here)
In the main, I do this;
public static void main(String[] args) {
int num[] = {0, 1, 2, 3, 4};
addArray(num);
System.out.println(num.length);
}
As you can see, the default array size (length) should be 5, but no matter how many times I invoke the method, it always print as 5.
Now I'm starting to think that static method does not allow the array from main to be resized ?
If it can't, do you have another way to resize an array by specifically using static method only ?