JavaDevNotes.com

Java Add To Array

Although a very old and dated data structure, array is still a very popular data structure to work with a collection of objects. This is because manipulation of arrays is very simple to learn and use. The only issue is it lacks advance features than can be found in the Collections API. For this tutorial, we will show how to Add elements to an Array in Java.

Java Add To Array Using Wrong Approach

Assume that we have an existing array and we want to add items to the end, for example:

int[] myArray = { 10, 30, 15 };

The first element is at index 0, the second is at index 1, and the last item is at index 2. We want to add the value 50 to the end at index 3. The code below will not work:

package mytest;
public class Test {
    public static void main(String[] args) {
        int[] myArray = { 10, 30, 15 };
        myArray[3] = 50;
    }
}

Because it will throw an ArrayIndexOutOfBoundsException at the line we try to assign the value 5.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
	at mytest.Test.main(Test.java:5)
This is because arrays have fixed length and we can't just add arbitrarily outside the bounds, or else we get Exception.

Java Add To Array By Recreating The Array

The simplest solution is just to create a new data structure that has more length. For example, we will increase the length by 1. See the code below:

package mytest;
import java.util.Arrays;
public class Test {
    public static void main(String[] args) {
        int[] myArray = { 10, 30, 15 };
        int[] tempArray = new int[myArray.length + 1];
        for (int i = 0; i < myArray.length; i++) {
            tempArray[i] = myArray[i];
        }
        tempArray[3] = 50;
        myArray = tempArray;
        System.out.println(Arrays.toString(myArray));
    }
}

The output is the expected result below:
[10, 30, 15, 50]
Let's inspect little by little, these lines creates a temporary array that is larger by 1 element. Meaning if myArray has length of 3, the tempArray has length of 4. It is hard not to create a new array as we might lose the data of myArray if we just assign a new instance to it.
int[] myArray = { 10, 30, 15 };
int[] tempArray = new int[myArray.length + 1];
These lines transfers the existing items from the original array to the new array. It copies the three elements.
for (int i = 0; i < myArray.length; i++) {
    tempArray[i] = myArray[i];
}

And then we append the last one to the end

tempArray[3] = 50;

Sine the temp array contains what we want, we can assign it back to our original array.

myArray = tempArray;