Growing an Array in Java
Suppose you have an array of some type that is full, and you want to grow it.
Code: JAVA
Employee[] a = new Employee[100];
// array is full
int newLength = a.length * 11 / 10 + 10;
Employee[] newArray = new Employee[newLength];
System.arraycopy(a, 0, newArray, 0, a.length);
a = newArray;
Code: JAVA
static Object[] arrayGrow(Object[] a) // not usefull
{
int newLength = a.length * 11 / 10 + 10;
Object[] newArray = new Object[newLength];
System.arraycopy(a, 0, newArray, 0, a.length);
return newArray;
}
Code: JAVA
a = (Employee[]) arrayGrow(a); // throws ClassCastException.
Code: JAVA
static Object arrayGrow(Object a) // useful
{
Class cl = a.getClass();
if (!cl.isArray()) return null;
int length = Array.getLength(a);
int newLength = length * 11 / 10 + 10;
Class componentType = a.getClass().getComponentType();
Object newArray = Array.newlnstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, length);
return newArray;
}
Typical usage:
Code: JAVA
Employee[] a = new Employee[100]; . . . . .// array is full
a = (Employee[]) arrayGrow(a);
Code: JAVA
int[] ia = ( 1, 2, 3, 4 };
ia = (int[])arrayGrow(a);


