ArrayLists
Use ArrayList methods, generic types, traversal, insertion, removal, shifting, and common mutation pitfalls.
A lesson of AP Computer Science A, in Arrays, ArrayLists, and 2D Arrays, about 10 minutes.
Arrays and ArrayLists
By the end of this lesson, you will be able to declare and use arrays, traverse arrays with loops, use 2D arrays, and work with the ArrayList class.
Arrays
int[] scores; // declaration (no array yet)
scores = new int[5]; // creates array of 5 ints (all initialized to 0)
// Declaration + creation:
int[] grades = new int[10];
String[] names = new String[20]; // all initialized to null
// Declaration + initialization (literal):
int[] values = {10, 20, 30, 40, 50};
Array: a fixed-size, ordered collection of elements of the same type.
Declaration and creation:
Index: arrays are zero-indexed — first element is at index 0; last is at index length - 1.
int[] arr = {10, 20, 30, 40, 50};
arr[0] // 10 (first element)
arr[4] // 50 (last element)
arr[5] // ArrayIndexOutOfBoundsException!
arr.length // 5 (length is a property, NOT a method call — no parentheses!)
Traversing Arrays
int[] scores = {85, 92, 78, 95, 88};
// Print all elements:
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
for loop:
Enhanced for loop (for-each): simpler when you don't need the index.
for (int score : scores) {
System.out.println(score);
}
When to use which:
- Use regular
forwhen you need the index (comparing adjacent elements, modifying elements, nested loops) - Use enhanced
forwhen you just need to read each value
Common Array Algorithms
int max = arr[0]; // start with the first element, NOT 0 (array might be all negative)
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
Find the maximum:
Calculate the sum/average:
int sum = 0;
for (int val : arr) {
sum += val;
}
double avg = (double) sum / arr.length;
Count elements meeting a condition:
int count = 0;
for (int val : arr) {
if (val > 80) count++;
}
Reverse an array:
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}