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

There is a Mobile Optimized version of this page (AMP). Open Mobile Version.

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.

Author: Dean Williams

I'm a Web Developer, Graphics Designer and Gamer, this is my personal site which provides PHP programming advice, hints and tips

  • Porfirio

    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.

  • Yeah that is another approach I should have mentioned, however an ArrayList is a little slower and why use it just for the novelty of being able to resize it? I think the ArrayList is good but only when you actually need to use the features to there full.