Skip to content
Advertisement

Resize an Array while keeping current elements in Java?

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement