Card 06/ 08
All 8 cards
GotchaDifficulty: Intermediate1 min
Why You Cannot Make an Array One Element Longer
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.