Arrays Have a Fixed Size
Let’s take a closer look at the fixed size property.
When we create an array in Java, we need to specify its size upfront. For example:
int[] numbers = new int[5]; // Creates an array of size 5
Once the array is created, we cannot change its size. If we want to add more elements than the array can hold, we have to create a new array with a larger size and copy the existing elements over:
// Assume newSize > oldArray.length
public static int[] resize(int[] oldArray, int newSize) {
int[] newArray = new int[newSize];
for (int i = 0; i < oldArray.length; i++) {
newArray[i] = oldArray[i]; // Copy elements to the new array
}
return newArray;
}
// Example usage:
int[] numbers = new int[5];
// ... fill the array with values ...
numbers = resize(numbers, 10); // Resize to hold more elements
Resizing an array is therefore a costly operation. It creates a new array and copies every element from the old array into the new one, so the work grows with the number of elements we are holding.
If we allocate a small array, we have to resize as soon as we run out of room. If we allocate a large array so that we do not have to resize, we are holding memory we may never use.
Solution
Here is a possible implementation of the resize method that can handle both growing and shrinking the array:
// Assume newSize > 0
public static int[] resize(int[] oldArray, int newSize) {
int[] newArray = new int[newSize];
int elementsToCopy = Math.min(oldArray.length, newSize);
for (int i = 0; i < elementsToCopy; i++) {
newArray[i] = oldArray[i]; // Copy elements to the new array
}
return newArray;
}
The programmer using the array has to track how full it is, decide when to resize, call resize, and remember to reassign the variable. That is bookkeeping that has nothing to do with the problem being solved. Suppose you are using the array to hold student grades and compute their average. Your problem is the grades and the average. Tracking how full the array is and copying elements into a bigger one is extra work the storage forces on you. In the next section we move that bookkeeping inside a data structure so the programmer does not have to do it.