How to double the size of an array
Solution 1
Either set and return the tmp variable as described by Kon, or you pass in arr
by reference to make changes to it persist outside of the resize function:
private static void resize(ref int[] arr) { .... }
and call it like
resize(ref arr);
Solution 2
Setting arr = tmp
does not do what you think it does. You're simply pointing the local variable arr
in the resize()
method to the local variable tmp
. What you want to do is return tmp
and assign it to arr
outside of the method.
if(arr_size==arr.length){
arr = resize(arr);
And change the resize()
method signature to
private static int[] resize(int[] arr) {
//Resize
return tmp;
}
The key thing to take away is that: When passing an object reference to a method in Java, you're passing a copy of that object's reference, which can be thought of as a copy of the location in memory of that object. All such manipulations to this REFERENCE in the called method won't take effect outside of the method. However, you CAN manipulate the actual object itself because, as I said, the reference is pointing to the same place in memory with the exact same object.
But changing a copy of a location in memory to point to a new location in memory does not cause the original calling object reference to point to that same location
Solution 3
try this :
private static int[] resize(int[] arr) {
int[] tmp = new int[2*arr.length];
System.arraycopy(tmp,0,arr,0,arr.length);
System.out.println(tmp.length);
return tmp;
}
Jason
Updated on April 18, 2020Comments
-
Jason about 4 years
I have to implement an array that takes its elements from a random generator. Whenever the array reaches it's last element a method resize() will be called to increase the size of the array. In my code every thing goes alight until invoking resize() method, it does not do any effect on the size of the array. It supposed to increase the size of the array to allow more elements to be entered.
for (int j=0; j<arr.length-1; j++) { random= generator.nextInt(arr.length*4) ; arr[j]=random; } if(arr_size==arr.length){ resize(arr); for (int h=0; h<(arr.length-1)*2; h++) { random= generator.nextInt(arr.length*4) ; arr[h]=random;} }
Here is resize():
private static void resize(int[] arr) { int[] tmp = new int[2*arr.length]; System.arraycopy(arr,0,tmp,0,arr.length); arr = tmp; }
-
Kumar about 10 years@Kon, just saw that and Updated with my answer
-
MarredCheese over 6 years
ref
is not valid Java. Maybe you were thinking of C#? -
HomeworkHopper over 2 yearsThis question is in regards to the Java programming language, but your answer appears to be using a different language.