How do you change the size of an array

suggest change

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:

  1. create a new array with size 4,
  2. copy the existing 3 elements of the old array to the new array at offsets 0, 1 and 2, and
  3. add the new element to the new array at offset 3.

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.

A better alternative to resizing an array

There are two major drawbacks to 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 from the Java SE library or a third-party library. The collections framework provides List, Set, and Map implementations with different costs. ArrayList is the closest to a plain array: get and set are O(1), search by value is O(N), and insertion or deletion at an arbitrary index is O(N). Resizing does not require you to update every reference, because callers keep the same list object.

(ArrayList grows the backing array by half, to 1.5 times the old capacity, not by doubling it. Geometric growth still makes the resize cost per append O(1) when it is amortized over the life of the list. A plain array can use the same strategy.)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents