Java: Resize Array’s & Multi-Dimensional Array’s

One useful feature in most programming languages is the ability to resize an array if you need more allocations for data, for instance in VB.NET you would resize an array like this:

Dim myArray(4) As Integer

Redim Preserve myArray(10) As Integer

 

In Java however it’s a different story… Java arrays cannot be resized dynamically and another solution must be found to accomplish this requirement. Below I have created a function which will take your array and “resize” it into a new size so you put more data into it, all it does is create a new array with the new size you require and copy all your data from the old array into the new array which is then returned from the function.

The Function

/**
 * Reallocates an array with a new size, and copies the contents
 * of the old array to the new array.
 * By Dean Williams - http://dean.resplace.net
 * @param oldArray the array to resize.
 * @param newSize the new array size.
 * @return  The resized array.
 */
 public static Object resizeArray(Object oldArray, int newSize) {
 int oldSize = java.lang.reflect.Array.getLength(oldArray);
 Class elementType = oldArray.getClass().getComponentType();
 Object newArray = java.lang.reflect.Array.newInstance(elementType,newSize);
 int preserveLength = Math.min(oldSize,newSize);

 if (preserveLength > 0) {
 System.arraycopy(oldArray,0,newArray,0,preserveLength);
 }

 return newArray;
 }

Resize array example:

int[] arr = {1,2,3};

arr = (int[])resizeArray(arr,5);
arr[3] = 4;
arr[4] = 5;

 

Resize Multi-Dimensional array example:

int arr[][] = new int[2][3];

arr = (int[][])resizeArray(arr,15);

for (int i=0; i<arr.length; i++) {
 if (arr[i] == null)
 arr[i] = new int[25];

} else {

 arr[i] = (int[])resizeArray(arr[i],25);

}

// new array is [15][25]

 

If you use this snippet please keep the credit in your code, also feel free to comment and let me know if this was useful or if you have any suggestions/comments.

Facebooktwitterredditpinterestlinkedinmail
Author: Dean WilliamsI'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips

Post Tags:
0 0 votes
Article Rating
Subscribe
Notify of
2 Comments
Inline Feedbacks
View all comments

Hi bud!

When i need arrays that can be resized in Java i use ArrayList: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Not the same thing but works.