Resize an arrayFrom WikiJava
This example shows how to dynamically resize an array by copying it into a new bigger one.
the articleArrays cannot be resized dynamically. If you want a dynamic data structure with random access, you use a Collection (Map, ArrayList,...). If you need to expand, you can use System.arraycopy() method to copy the content of an array to another one. ArrayUtils.javaimport java.lang.reflect.Array; public class ArrayUtils { public static void main (String arg[]) { String s[] = new String[20]; System.out.println("The s array length is " + s.length); // 20 s = (String[])ArrayUtils.expand(s); System.out.println("The s array length is " + s.length); // 30 int i[] = {1 ,2 ,3, 4}; System.out.println("The i array length is " + i.length); // 4 i = (int[])ArrayUtils.expand(i); System.out.println("The i array length is " + i.length); // 6 } public static Object expand(Object a) { Class cl = a.getClass(); if (!cl.isArray()) return null; int length = Array.getLength(a); int newLength = length + (length / 2); // 50% more Class componentType = a.getClass().getComponentType(); Object newArray = Array.newInstance(componentType, newLength); System.arraycopy(a, 0, newArray, 0, length); return newArray; } } See Alsoresize an array using ArrayList, Real's Java How To |
