Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize an Array while keeping current elements in Java?

Tags:

java

arrays

I have searched for a way to resize an array in Java, but I could not find ways of resizing the array while keeping the current elements.

I found for example code like int[] newImage = new int[newWidth];, but this deletes the elements stored before.

My code would basically do this: whenever a new element is added, the array largens by 1. I think this could be done with dynamic programming, but I'm, not sure how to implement it.

like image 679
Mihai Bujanca Avatar asked Nov 02 '12 14:11

Mihai Bujanca


People also ask

Can we change the size of an array at run time in Java?

Size of an array If you create an array by initializing its values directly, the size will be the number of elements in it. Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array.

How can we change the size of array without losing data?

You can use the ReDim statement to change the size of one or more dimensions of an array that has already been declared. If you have a large array and you no longer need some of its elements, ReDim can free up memory by reducing the array size. On the other hand, if your array needs more elements, ReDim can add them.

Can arrays be dynamically resized?

A dynamic array is an array with a big improvement: automatic resizing. One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time.


2 Answers

You can't resize an array in Java. You'd need to either:

  1. Create a new array of the desired size, and copy the contents from the original array to the new array, using java.lang.System.arraycopy(...);

  2. Use the java.util.ArrayList<T> class, which does this for you when you need to make the array bigger. It nicely encapsulates what you describe in your question.

  3. Use java.util.Arrays.copyOf(...) methods which returns a bigger array, with the contents of the original array.

like image 145
Steve McLeod Avatar answered Oct 14 '22 02:10

Steve McLeod


Not nice, but works:

    int[] a = {1, 2, 3};     // make a one bigger     a = Arrays.copyOf(a, a.length + 1);     for (int i : a)         System.out.println(i); 

as stated before, go with ArrayList

like image 43
jlordo Avatar answered Oct 14 '22 03:10

jlordo