Reputation: 173
If a method is passed a reference to an array, is there any way to alter the size of that array so that the array reference that was passed in will refer to the new, larger array?
I don't entirely understand the question. I think it means that I will ultimately have to create a new string in the method that replaces the old one. Any Help will be appreciated. This is my code thus far:
import java.util.Arrays;
public class ASize {
static int num[] = {32, 34, 45, 64};
public static void main(String[] args){
alterThatSize(num);
System.out.println(Arrays.toString(num));
}
public static void alterThatSize(int bre[]){
for(int i = 0; i < 8; i++){
bre[i] = 1 + i;
}
}
}
Upvotes: 1
Views: 503
Reputation: 100149
It's not possible to do this because of two reasons. First, Java arrays have fixed length which cannot be changed since array is created. Second, Java is pass-by-value language, so you cannot replace the passed reference with the reference to the new array. Usually such task is solved by using the return value:
static int[] expandArray(int[] arr, int newSize) {
int[] newArr = new int[newSize];
System.arraycopy(arr, 0, newArr, 0, arr.length);
return newArr;
}
Use it like this:
num = expandArray(num, newSize);
Upvotes: 2