[Solved] Resizeing an Array [closed]


You can probably understand from the other answers that it is not possible to change the size of an array after you create it. When you say

int [] A = new int[5]; 

what you are really saying is that you have an object called ‘A’ and you want to put in there an array of integers and size 5. You can not change that array. You can though put in ‘A’ a new array of integers and size 3 just by saying:

A = new int[3];

If you do that (provided you don’t have other references to it) the old array will be thrown away by the garbage collector. You just need to copy whatever you had in that old array to the new one and you are done! This will also change the length.

Here’s a little test code:

int [] a = new int[5];
a[0] = 2;
a[1] = 5;
a[2] = 1;
a[3] = 6;
a[4] = 0;
println(a.length); // prints 5
int [] temp = new int[3];
System.arraycopy(a,0,temp,0,temp.length);
a = temp;
temp = null;
println(a.length); //prints 3

This is considered an ugly approach because you can do this much more elegantly using an ArrayList, which can be resized directly;

Technically this is copying the array into a new array, but it might be what you are looking for

3

solved Resizeing an Array [closed]