Resize an arrayTag(s): Language
Arrays 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.
import java.lang.reflect.Array; public class ArrayUtils { private ArrayUtils() {} 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; } 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 } }
But a better way is to use a Vector or an ArrayList. ArrayList is roughly equivalent to Vector, except that it is unsynchronized.
import java.util.ArrayList; public class ArrayListDemo { public static void main (String arg[]) { ArrayListDemo x = new ArrayListDemo(); x.doit1(); x.doit2(); } public void doit1() { // single dimension ArrayList list = new ArrayList(); list.add("a"); list.add("b"); int size = list.size(); // 2 System.out.println("Array 1 " +list.get(0); // a } public void doit2() { // multi dimensions ArrayList list = new ArrayList(); ArrayList l1 = new ArrayList(); l1.add("a"); ArrayList l2 = new ArrayList(); l2.add("b"); ArrayList l3 = new ArrayList(); l3.add("c"); list.add(l1); list.add(l2); list.add(l3); int size1 = list.size(); // 3 int size2 = ((ArrayList)list.get(0)).size(); // 1 System.out.println("Array 2 " + ((ArrayList)list.get(1)).get(0)); // b } }
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com