HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Push an item onto the end of array in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
itemthearrayjavapushontoend

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.

Code Snippets

int[] newArray = (int[]) Array.newInstance(oldArray.getClass().getComponentType(), len + 1);
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;
}

Context

StackExchange Code Review Q#149801, answer score: 5

Revisions (0)

No revisions yet.