Tutorial Java – # 4.1 How to add a new element to a Java array

4 comments - This post in romanian

In this post we see what is the solution to the problem of adding a new element to an existing array. As we saw in the Java Tutorial 6 – #4 Arrays, arrays are objects which manage a homogeneous and compact list of items.

Because the list of elements is a compact memory area in Heap, the answer to the question of how we add a new element is that it is NOT possible. Once constructed the array, with a finite number of elements, the space it occupies can not be resized.

So we can not reallocate or enlarge memory space already allocated. The only solution to add a new element to an array with n elements is:

  1. define a new array of size n+1;
  2. copy those n values into new array;
  3. the last element will be initialized with the new value;
  4. the array value (it is a reference) will be reinitialized with the address of the new list of values;
        //initial array
        int[] oldArray = {1,2,3,4,5};
        //new value
        int newValue = 10;
        //define the new array
        int[] newArray = new int[oldArray.length + 1];
        //copy values into new array
        for(int i=0;i < oldArray.length;i++)
            newArray[i] = oldArray[i];
        //another solution is to use 
        //System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
        //add new value to the new array
        newArray[newArray.length-1] = newValue;
        //copy the address to the old reference 
        //the old array values will be deleted by the Garbage Collector
        oldArray = newArray;

If the application requires a lot of operations, like this one, it is better to use a data structure that is more efficient on adding or removing elements. In Java, this could be the ArrayList collection (more about collections in a new post – Tutorial Java 6 – Contents)


  1. #1 by bob on December 31st, 2010

    for(int i=0;i < oldArray.length;i++)
    newArray[i] = oldArray[i];

    should be written as

    System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);

(will not be published)