Thursday, 13th October 2011
Follow WikiJava on twitter now. @Wikijava

Resize an array

From WikiJava

Jump to: navigation, search


This example shows how to dynamically resize an array by copying it into a new bigger one.

Contents

the article

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.

ArrayUtils.java

import 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 Also

resize an array using ArrayList, Real's Java How To

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page


Comments on wikijava are disabled now, cause excessive spam.