Card 06/ 08
Why a Java Array Cannot Grow
Ten slots, an eleventh value, no method to call, and an exception when you try slot ten.
An array's length is fixed when it is created, so there is no way to add a slot. To hold more, you create a new, longer array and copy the old values into it, which is what Arrays.copyOf does.
You have an array of ten and an eleventh thing to put in it. There is no method to call, and assigning to slot ten throws:
int[] scores = new int[10];
scores[10] = 99;Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10An array's length is fixed when it is created, because the run of memory holding it was reserved at that size. Growing it would mean the slots after it were free, and nothing guarantees that.
What Arrays.copyOf does is the honest version of growing: it allocates a new, longer array, copies every element across, and hands the new one back. Your original is untouched, and the variable now points somewhere else.
int[] scores = new int[10];
scores = Arrays.copyOf(scores, 11);
scores[10] = 99;So reach for an array when the size is known and fixed, and reach for a List the moment it is not. Rebuilding an array by hand is work that a collection has already done, carefully.
← → move through sections and cards