Array Capacity and Length
The capacity of an Array is the number of elements it can hold. The length of an Array is the number of elements it currently holds.
If somebody asks you how long the Array is, what would your answer be?
There are two different answers you might have given.
- The number of elements the Array can hold.
- The number of elements the Array currently holds.
Both answers are correct, and both have very different meanings! It's important to understand the difference between them, and use them correctly. We call the first one the Capacity
of the Array, and the second one the Length
of the Array.
Capacity
The Capacity
of an Array is the number of elements it can hold. The capacity is fixed, and cannot be changed. Once you create an Array, you can only write elements into it, but you cannot change the capacity. If you want to write more elements into the Array, you'll need to create a new Array with a larger capacity.
Let's say we have created a new Array like this.
int[] numbers = new int[4];
Remembering that indexing starts at 0
, we can only insert items at array[0]
, array[1]
, array[2]
, array[3]
, array[4]
, and array[5]
. Trying to put an element anywhere else, such as array[-3]
, array[6]
, or array[100]
will cause your code to crash with an ArrayIndexOutOfBoundsException
!
The Capacity
of an Array in Java
can be checked by looking at the value of its length
attribute. This is done using the code arr.length
, where arr is the name of the Array. Different programming languages have different ways of checking the length of an Array.
int capacity = array.length;
System.out.println("The Array has a capacity of " + capacity);
Yup, it's a bit confusing that you need to access the capacity of an Array by using .length
. Unfortunately, this is just something you'll need to get used to.
Length
The other definition of Length
is the number of elements currently in the Array. This is something you'll need to keep track of yourself, and you won't get any errors if you overwrite an existing Element, or if you leave a gap in the Array.
// Create a new array with a capacity of 6.
int[] array = new int[8];
// Current length is 0, because it has 0 elements.
int length = 0;
// Add 3 items into it.
for (int i = 0; i < 3; i++) {
array[i] = i * i;
// Each time we add an element, the length goes up by one.
length++;
}
System.out.println("The Array has a capacity of " + array.length); // 8
System.out.println("The Array has a length of " + length); // 3