Push an item onto the end of array in Java

Posted on

Problem

I want to make a method arrayIntPush(3, {5,4,8}) that will return {5,4,8,3}.
This method seems to work:

public static int[] arrayIntPush(int item, int[] oldArray) {
    int len = oldArray.length;
    int[] newArray = (int[]) Array.newInstance(oldArray.getClass().getComponentType(), len + 1);
    System.arraycopy(oldArray, 0, newArray, 0, len);
    System.arraycopy(new int[] {item}, 0, newArray, len, 1);

    return newArray;
}

Is there a better way to do this that would be faster?

Solution

Is this really needed?

int[] newArray = (int[]) Array.newInstance(oldArray.getClass().getComponentType(), len + 1);

I would do something like:

public static int[] arrayIntPush(int item, int[] oldArray) {
    int len = oldArray.length;
    int[] newArray = new int[len+1];
    System.arraycopy(oldArray, 0, newArray, 0, len);
    newArray[len] = item;

    return newArray;
}

So for an array of length 10 you make a new array or length 11, copy all existing data into it and then assign the last index to the item.

Before Java 8, an even more simplified way is to use Arrays.copyOf(int[], int):

private static int[] push(int[] array, int value) {
    int[] result = Arrays.copyOf(array, array.length + 1);
    result[array.length] = value;
    return result;
}

Java 8’s IntStream gives you a way to have only a single return statement:

private static int[] push(int[] array, int value) {
    return IntStream.concat(Arrays.stream(array), IntStream.of(value)).toArray();
}

Small tip: Since you are pushing a new value to the end of the array, you may want to consider reordering the method parameters so that the incoming value is indeed to the right of the array.

Just to be an annoyance and since this is code review not give me an answer… the more important question is what is the actual use case of this method? Do you have control over the code that is calling it or is this a library method?

I ask because Java already has data structures to handle adding and removing of elements (Vector and ArrayList). If instead you could shift your code to using one of those, not only do you save a memory allocation and memory duplication every time the method is run you will decrease it significantly increasing your performance drastically. It’s important to keep in mind that both these structures use Array as their backing data structure… it just wraps it with helpful methods like the one you have written.

If you do this, your old code would look something like this:

int [] data = [1,2,3,4];
data = arrayIntPush(5, data);

To

Vector<int> data = new Vector<int>([1,2,3,4]);
data.Add(5);

Or something like that. It’s been a while since I’ve done Java 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *