Tricky Tricks ›› Programming Tricks ›› Java Tricks ›› Hassle Free Array Growth

Hassle Free Array Growth

Java Programming Tricks

Hassle-free array growth:

 Suppose you have an array of some type that is full, and you 
 want to grow it.
 
 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;
 
 
 That gets boring really quickly. Let's try to make it generic. 
 
 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; 
 
 }
 
 Problem: Return type is Object[], not Employee [] . 
 
 a = (Employee[]) arrayGrow(a); // throws ClassCastException. 
 
 
 Tip 
 
 Use reflection to make a new array of the same type:
 
 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:
 
 Employee[] a = new Employee[100]; . . . . .// array is full 
 
 a = (Employee[]) arrayGrow(a); 
 
 
 Note 
 
 This arrayGrow method can be used to grow arrays of any type, not just arrays 
 of objects. 
 
 int[] ia = ( 1, 2, 3, 4 }; 
 
 ia = (int[])arrayGrow(a); 
 
 Note that the parameter of arrayGrow is declared to be of type object, not an 
 array of objects 
 
 (Object [] ). The integer array type int [] can be converted to an object, but 
 not to an array of objects!
 

Partners