Nov 18

You need to create a new array and copy the existing array into the new array

If using Java 1.6+:

   arrayToResize = Arrays.copyOf(arrayToResize, arrayToResize.length * 2);

See the following examples for earlier versions.

public static int[] resizeArray(int[] arrayToResize) {
	// create a new array twice the size
	int newCapacity = arrayToResize.length * 2;
	int[] newArray = new int[newCapacity];

	System.arraycopy(arrayToResize, 0, 
            newArray, 0, arrayToResize.length);
	return newArray;
}

public static String[] resizeArray(String[] arrayToResize) {
	// create a new array twice the size
	int newCapacity = arrayToResize.length * 2;
	String[] newArray = new String[newCapacity];

	System.arraycopy(arrayToResize, 0, 
          newArray, 0, arrayToResize.length);
	return newArray;
}

public static <T> T[] resizeArray(T[] arrayToResize) {
	// create a new array twice the size
	int newCapacity = arrayToResize.length * 2;
	T[] newArray = (T[]) Array.newInstance(
           arrayToResize[0].getClass(), newCapacity);

	System.arraycopy(arrayToResize, 0, 
           newArray, 0, arrayToResize.length);
	return newArray;
}

written by objects \\ tags:


One Response to “How do I resize a Java array?”

  1. RonRon Says:

    I think you better remind the readers they can also use the ArrayList to solve the array resize problem.

Leave a Reply

You must be logged in to post a comment.