Show contents
Chapter 5 of 6 · 20 min
Arrays and ArrayList
By the end of this chapter, you'll be able to
- Create an array, read and change its boxes, know its length
- Go through an array or a list with a for-each loop
- Add, read and remove items in an ArrayList
- Avoid the out-of-bounds index error
Arrays
void main() {
int[] sales = {120, 95, 140, 80, 160};
IO.println("Monday: " + sales[0] + ", Friday: " + sales[4]);
IO.println("Number of days: " + sales.length);
sales[3] = 85; // correcting an entry
int total = 0;
for (int s : sales) {
total += s;
}
IO.println("Total: " + total);
IO.println(Arrays.toString(sales));
}
Monday: 120, Friday: 160
Number of days: 5
Total: 600
[120, 95, 140, 85, 160]
int[]is an array of integers. Its size is fixed when it's created: here 5 boxes.- The boxes are numbered from 0 to length - 1:
sales[0]is the first,sales[4]the last. This number is the index. new int[7]creates an array of 7 boxes that are all 0.- The for-each loop
for (int s : sales)goes through each item, without an index. Arrays.toString(array)produces a readable text. Displaying an array directly would give something like[I@1b6d3586, a useless internal address.
ArrayList: a list that grows
When you don't know the number of items in advance, use an ArrayList:
size() gives the number of items. A list displays directly in a readable way.
Text description of the animation
- We manage the guest list for a party.
- An empty list of Strings is created.
- add adds at the end.
- The list grows by itself.
- Three guests.
- remove removes the item equal to "Omar". The following ones shift: Chen moves to index 1.
- size() gives the number of items. A list displays directly in a readable way.
void main() {
ArrayList<Double> temperatures = new ArrayList<>();
temperatures.add(21.5);
temperatures.add(24.0);
temperatures.add(19.0);
temperatures.set(2, 19.5); // replaces the item at index 2
IO.println("First reading: " + temperatures.get(0));
IO.println("Contains 24? " + temperatures.contains(24.0));
double max = temperatures.get(0);
for (double t : temperatures) {
if (t > max) {
max = t;
}
}
IO.println("Maximum: " + max);
}
First reading: 21.5
Contains 24? true
Maximum: 24.0
- The type of the items is written between angle brackets:
ArrayList<String>,ArrayList<Double>. For numbers, you use the wrapper classesInteger,Double,Boolean… because a list only holds objects. Java converts automatically betweendoubleandDouble. new ArrayList<>(): Java deduces the type of the items from the declaration.add,get(i),set(i, value),remove,size(),contains,isEmpty()are the common operations.List.of("a", "b")creates an unmodifiable list, handy for fixed data.
Your turn
Worked exercise
Worked exercise: the step counter
A step counter recorded the week's steps: {8200, 12500, 6400, 10000, 15300, 9100, 11800}. Write a program that displays the number of days the 10,000-step goal was reached, the number of the best day (from 1 to 7) and the list of successful days: 4 successful days, Best day: 5 (15300 steps) and Successful days: [2, 4, 5, 7].
Hint 1
for: you need the index to know the day number (i + 1).Hint 2
ArrayList<Integer>, and keep the index of the maximum in a variable.Show the solution and common mistakes
void main() {
int[] steps = {8200, 12500, 6400, 10000, 15300, 9100, 11800};
final int GOAL = 10_000;
var successful = new ArrayList<Integer>();
int best = 0;
for (int i = 0; i < steps.length; i++) {
if (steps[i] >= GOAL) {
successful.add(i + 1);
}
if (steps[i] > steps[best]) {
best = i;
}
}
IO.println(successful.size() + " successful days");
IO.println("Best day: " + (best + 1) + " (" + steps[best] + " steps)");
IO.println("Successful days: " + successful);
}
4 successful days
Best day: 5 (15300 steps)
Successful days: [2, 4, 5, 7]
The _ in 10_000 is allowed in Java numbers: it makes large numbers more readable.
Common mistakes:
- Testing
steps[i] > GOAL: day 4, with exactly 10,000 steps, wouldn't be counted. - Displaying
bestinstead ofbest + 1: indexes start at 0, but days are numbered from 1.
Summary
- 1An array (int[]) has a fixed size; its indexes go from 0 to length - 1.
- 2An ArrayList grows with add; get, set, remove and size handle it.
- 3Lists hold objects: Integer, Double… instead of int, double.
- 4for (T x : collection) goes through each item without an index.
- 5An invalid index throws an exception that gives the faulty index and the size.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.