Renigunda Renigunda - 6 months ago 5x
Java Question

Dynamic resizing of Array in Java

I wanted to use Dynamic Array in Java,

I will be declaring the array statically,where i will input values into the array ,once the array gets full i will reintialize the array size.

Whether the contents of the array will be removed or it will be maintained.

The contents are deleted in my program ,whether that is expected or not ?

class a
static int arr[]=new int[10];
public static void main(String args[])
int N=35;
arr=new int[N];



When you write:

arr=new int[N]

you actually discard your array object and create a new array of int of size N. This new object will not contain your previous array's values.

If you create a larger array, you must copy the previous values to it. Better still, use one of Java's data structures such as Vector<Integer> or ArrayList<Integer>. These use dynamic arrays, but you don't have to know about it and shouldn't worry - they just work...