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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With