Java Growable integer array

A growable int array

The following code implements a growable array. It uses a real array as the backend. Whenever the array need more space it just create a new array with double size and uses the System.copyarray to copy old array to new array.


public class Main{
  public static void main(String[] args) {
    IntList list = new IntList();
    for(int i=0;i<15;i++){
      list.add(i);/*from   w  w  w  . j  av  a 2s.com*/
    }
    System.out.println(list.size());
  }  
  
}
class IntList {
  private static final int DEFAULT_SIZE = 10;

  private int[] data = new int[DEFAULT_SIZE];
  private int numElements;

  public void add(int f) {
    if (numElements == data.length) {
      resize(1 + numElements);
    }
    data[numElements++] = f;
    assert numElements <= data.length;
  }

  public int size() {
    return numElements;
  }

  public int get(int index) {
    if (index >= numElements) {
      throw new ArrayIndexOutOfBoundsException(index);
    }
    return data[index];
  }

  public void put(int index, int val) {
    if (index >= numElements) {
      throw new ArrayIndexOutOfBoundsException(index);
    }
    data[index] = val;
  }

  public void trim() {
    if (data.length > numElements) {
      int[] newData = new int[numElements];
      System.arraycopy(data, 0, newData, 0, numElements);
      data = newData;
    }
  }

  public int[] getData() {
    return data;
  }

  private void resize(int minCapacity) {
    int newCapacity = 2 * data.length;
    if (newCapacity == 0) {
      newCapacity = DEFAULT_SIZE;
    }
    if (newCapacity < minCapacity) {
      newCapacity = minCapacity;
    }
    int[] newData = new int[newCapacity];
    System.arraycopy(data, 0, newData, 0, data.length);
    data = newData;
  }
}

The code above generates the following result.

From the code we can see that the initial size of the list is 10 and we use the for loop in the Main class to insert 15 elements. The final size of the list is 15 which is enlarged automatically.

Next chapter...

What you will learn in the next chapter:

  1. How to implement a LinkedList in Java
Home »
  Java Tutorial »
    Java Langauge »
      Java Data Structures
Java Growable integer array
Java LinkedList
Java Binary Tree
Java Tree