AP Computer Science A · Data collections
Arrays
1Creating arrays
An array stores a fixed number of values of the same type, accessed by index from 0 to length - 1.
int[] scores = new int[5]; // five 0s
String[] days = {"Mon", "Tue", "Wed"}; // initialiser list
scores.lengthis 5 (a field, no parentheses).- New arrays hold default values: 0, 0.0, false or null.
- The size cannot change after creation.
- Accessing an index outside 0 to
length - 1throws ArrayIndexOutOfBoundsException.
Array elements are numbered from 0 to length − 1
Check yourself
For int[] a = new int[8];, the last valid index is:
Show the answer
7
length − 1.
2Traversing arrays
Indexed for loop: gives access to the index, can change elements.
for (int i = 0; i < arr.length; i++) {
arr[i] *= 2;
}
Enhanced for loop (for-each): simpler, read-only for elements.
for (int value : arr) {
sum += value;
}
Assigning to the loop variable in a for-each loop (value = 0;) does not change the array, because value is a copy of each element.
Check yourself
Which loop can set every element of an int array to 0?
Show the answer
for (int i = 0; i < a.length; i++) a[i] = 0;
Needs the index.
3Standard array algorithms
- Sum and average.
- Minimum / maximum: initialise to
arr[0], not 0 (all values might be negative). - Count elements meeting a condition.
- Check whether any/all elements meet a condition (return early).
- Shift or rotate elements; reverse an array by swapping
arr[i]andarr[arr.length - 1 - i]for the first half. - Adjacent pairs:
for (int i = 0; i < arr.length - 1; i++)comparesarr[i]andarr[i + 1].
find the largest value.
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
}
Check yourself
Why initialise max to arr[0] rather than 0?
Show the answer
All values might be negative
0 might exceed every element.
4Arrays and references
An array variable is a reference. Assigning one array variable to another makes an alias, not a copy:
int[] a = {1, 2, 3};
int[] b = a;
b[0] = 99; // a[0] is now 99 too
Passing an array to a method passes the reference, so the method can change the caller's elements.
Check yourself
After int[] b = a; b[1] = 5;, what is a[1]?
Show the answer
5
Same array.
5Going deeper: the standard algorithms, and the errors to avoid
Essentials
- An array has a fixed length, set when it is created:
int[] a = new int[5];orint[] a = {3, 8, 1};. a.length(no parentheses) is the number of elements.- Indices run from 0 to
a.length - 1. Anything else throws an ArrayIndexOutOfBoundsException. - Elements created with
newhold defaults: 0, 0.0, false or null.
Two ways to traverse
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
for (int value : a) {
System.out.println(value);
}
The enhanced for loop gives each element in turn as a copy.
- Use it to read every element.
- You cannot use it to change elements of a primitive array: assigning to
valuechanges only the copy. - It gives no index, so it cannot compare neighbors, go backward or skip.
Standard algorithms (know these by heart)
Sum and average
int sum = 0;
for (int v : a) {
sum += v;
}
double avg = (double) sum / a.length;
Maximum (and where it is)
int maxIndex = 0;
for (int i = 1; i < a.length; i++) {
if (a[i] > a[maxIndex]) {
maxIndex = i;
}
}
Start from the first element, not from 0: the array might hold only negatives.
Count matches; does any element satisfy a condition? (return true as soon as one is found; return false after the loop); do all satisfy it? (return false as soon as one fails; return true after the loop).
Compare neighbors: stop one early.
boolean increasing = true;
for (int i = 0; i < a.length - 1; i++) {
if (a[i] >= a[i + 1]) {
increasing = false;
}
}
Reverse in place: swap ends, moving inward; go only halfway.
for (int i = 0; i < a.length / 2; i++) {
int temp = a[i];
a[i] = a[a.length - 1 - i];
a[a.length - 1 - i] = temp;
}
Looping the whole length would swap everything back.
Shift left by one (dropping the first, or rotating it to the end)
int first = a[0];
for (int i = 0; i < a.length - 1; i++) {
a[i] = a[i + 1];
}
a[a.length - 1] = first;
To shift right, loop backward, or each value would be overwritten before it is copied.
Worked example (trace): what does a hold afterward, starting from {2, 4, 6, 8}?
for (int i = 1; i < a.length; i++) {
a[i] = a[i] + a[i - 1];
}
- i = 1: a[1] = 4 + 2 = 6.
- i = 2: a[2] = 6 + 6 = 12 (using the updated a[1]).
- i = 3: a[3] = 8 + 12 = 20.
- Result: {2, 6, 12, 20}: running totals.
Arrays are objects
- An array variable holds a reference.
b = a;makes an alias, not a copy. - Passing an array to a method lets the method change its elements.
a == btests whether they are the same array, not whether the contents match.- To copy, create a new array and copy element by element.
Arrays of objects: String[] names = new String[3]; creates three null references, not three strings. Calling names[0].length() before assigning throws a NullPointerException.
Returning an array: a method may build and return a new array, such as one containing only the even values. Count first to find the size, create the array, then fill it using a separate index for the new array.
Common mistakes
i <= a.length(one step too far).a.length()with parentheses (that is for Strings).- Using
a[i + 1]without stopping atlength - 1. - Trying to modify elements through the enhanced for loop variable.
- Initializing a maximum to 0.
- Reversing with a full-length loop.
- Thinking
b = acopies the array.
Check yourself
Which loop header correctly visits every pair of adjacent elements a[i] and a[i + 1]?
Show the answer
for (int i = 0; i < a.length - 1; i++)
The last valid pair starts at index length − 2.
6For top marks
- Loop bounds:
i < arr.lengthfor full traversal;i < arr.length - 1when usingarr[i + 1]. - Use an indexed loop when you need positions or to modify elements; a for-each loop otherwise.
- Return from inside the loop when searching ("return true as soon as found"), and return the "not found" answer after the loop.
- Use
arr.length, never a hard-coded number.
check whether an array is sorted:
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) return false;
}
return true;
Check yourself
What is wrong with returning false in an else branch inside the "is sorted" loop on the first pair that is in order?
Show the answer
It would return after checking only the first pair
The answer is only known after the loop.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera