Renigunda Renigunda - 2 years ago 101
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];


Answer Source

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...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download