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.