11

Is it possible to append elements at the end of a primitive array in Java? For ex: if int[] a = new int[10]; is an array. How can i go on appending elements at the end?

Edit:
I do not want to use ArrayList for performance reason and want to stay with primitive arrays.

Pratik Khadloya
  • 12,509
  • 11
  • 81
  • 106
  • 7
    You can't. Arrays are static in length. – gtgaxiola Aug 26 '14 at 19:34
  • Use something appropriate from [`Collection`](http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html) family. – Markus Malkusch Aug 26 '14 at 19:35
  • 2
    What do you mean by "append" ? having them objects one-after-another in memory space ? simply being able to print the members of the array with the additional object ? increase the size of the array and add more elements ? do you want to add elements of different `type` ? – Nir Alfasi Aug 26 '14 at 19:36
  • @Pshemo not only primitives but the OP is referring to them... – gtgaxiola Aug 26 '14 at 19:38
  • 1
    possible duplicate of [append values dynamically into an long\[\] array](http://stackoverflow.com/questions/5144549/append-values-dynamically-into-an-long-array) – Raedwald Aug 26 '14 at 20:54

2 Answers2

7

A way to make an Array more dynamic is to create a method that creates a new longer array and replace the old one with it.

For example.

lets say you have an int[] of size 10 and it holds numbers 0 to 9:

int[] array = new int[10];
for(int i = 0; i < array.length; i++)
    array[i] = i;

Printing the contents of the array will output: 0 1 2 3 4 5 6 7 8 9

Now you can have a method like this:

private int[] appendArray(int[] array, int x){
    int[] result = new int[array.length + 1];

    for(int i = 0; i < array.length; i++)
        result[i] = array[i];

    result[result.length - 1] = x;

    return result;
}

and do the following

array = appendArray(array, 10);

Now printing the contents of the array will output: 0 1 2 3 4 5 6 7 8 9 10

Alternatively you can use an ArrayList that is basically doing a similar thing.

gkrls
  • 2,618
  • 2
  • 15
  • 29
3

Once created, the size of an array in Java is fixed.

If you want to have a dynamically sized storage, you will want to use an ArrayList.

The alternative is to create a new (larger) array and copy the contents of the old one, but keep in mind that this will be very expensive in both time and memory:

// this is a terrible idea, don't do it
public int[] append(int[] i, int newElement) {
    int[] copy = new int[i.length+1];
    System.arraycopy(i, 0, copy, 0, i.length);
    copy[i.length]= newElement;
    return copy;
}

This is effectively what an ArrayList is doing for you behind the scenes (albeit more efficiently), so if you're going to be adding very many elements, you'll want to start with a larger ArrayList than the default capacity of 10 elements.

azurefrog
  • 10,785
  • 7
  • 42
  • 56