The simple answer is that you cannot do this. Once an array has been created, its size cannot be changed. Instead, an array can only be "resized" by creating a new array with the appropriate size and copying the elements from the existing array to the new one.
String[] listOfCities = new String[3]; // array created with size 3.
listOfCities[0] = "New York";
listOfCities[1] = "London";
listOfCities[2] = "Berlin";
Suppose (for example) that a new element needs to be added to the listOfCities
array defined as above. To do this, you will need to:
There are various ways to do the above. Prior to Java 6, the most concise way was:
String[] newArray = new String[listOfCities.length + 1];
System.arraycopy(listOfCities, 0, newArray, 0, listOfCities.length);
newArray[listOfCities.length] = "Sydney";
From Java 6 onwards, the Arrays.copyOf
and Arrays.copyOfRange
methods can do this more simply:
String[] newArray = Arrays.copyOf(listOfCities, listOfCities.length + 1);
newArray[listOfCities.length] = "Sydney";
For other ways to copy an array, refer to the following example. Bear in mind that you need an array copy with a different length to the original when resizing.
There two major drawbacks with resizing an array as described above:
One alternative is to create the array with a large enough size to start with. This is only viable if you can determine that size accurately before allocating the array. If you cannot do that, then the problem of resizing the array arises again.
The other alternative is to use a data structure class provided by the Java SE class library or a third-party library. For example, the Java SE "collections" framework provides a number of implementations of the List
, Set
and Map
APIs with different runtime properties. The ArrayList
class is closest to performance characteristics of a plain array (e.g. O(N) lookup, O(1) get and set, O(N) random insertion and deletion) while providing more efficient resizing without the reference update problem.
(The resize efficiency for ArrayList
comes from its strategy of doubling the size of the backing array on each resize. For a typical use-case, this means that you only resize occasionally. When you amortize over the lifetime of the list, the resize cost per insert is O(1)
. It may be possible to use the same strategy when resizing a plain array.)