Implementing ArrayList Algorithms
The standard traversal algorithms applied to ArrayList objects: minimums, maximums, sums, and averages; property checks and counts; consecutive pairs and duplicates; shifting, rotating, and reversing; inserting and deleting; and traversing several collections at once.
There are standard ArrayList algorithms that utilize traversals to determine a minimum or maximum value; compute a sum or average; determine if at least one element, or all elements, have a particular property; determine the number of elements having a particular property; access all consecutive pairs of elements; determine the presence or absence of duplicate elements; shift or rotate elements left or right; reverse the order of the elements; insert elements; and delete elements. Some algorithms require multiple String, array, or ArrayList objects to be traversed simultaneously.
1Familiar Algorithms With List Syntax
Most ArrayList algorithms are the array algorithms with new syntax: list.get(i) replaces a[i], list.set(i, v) replaces assignment to an element, and list.size() replaces a.length. Enhanced for loops work the same way for reading every element.
A minimum or maximum starts from an actual element, list.get(0), and replaces it whenever a smaller or larger element appears. A sum adds every element; an average divides that sum by list.size(). For a list of Integer or Double objects, unboxing turns each element into a primitive for the arithmetic.
| Algorithm | ArrayList pattern |
|---|---|
| Minimum or maximum | Start at list.get(0); compare each element |
| Sum or average | Add each element; divide by list.size() |
| At least one has a property | Return true at the first match; false after the loop |
| All have a property | Return false at the first failure; true after the loop |
| Count with a property | Add 1 for each match |
| Consecutive pairs | i < list.size() - 1; compare get(i) and get(i + 1) |
| Duplicates | Nested loops, inner index starting at i + 1 |
| Shift or rotate | remove at one end, add at the other |
| Reverse | Swap get(i) and get(size − 1 − i) with set, for i < size / 2 |
| Insert | Find the index, then add(index, value) |
| Delete | Traverse backward and remove(i) each match |
Summarizing a List
Predict the output.
ArrayList<Double> temps = new ArrayList<Double>();
temps.add(18.5);
temps.add(22.0);
temps.add(16.5);
temps.add(21.0);
double max = temps.get(0);
double min = temps.get(0);
double sum = 0.0;
for (double t : temps)
{
sum += t;
if (t > max)
{
max = t;
}
if (t < min)
{
min = t;
}
}
System.out.println(max + " " + min);
System.out.println(sum / temps.size());
22.0 16.5
19.5
- 1Start from a real element.
maxandminboth begin attemps.get(0). - 2Unboxing in the loop.
for (double t : temps)unboxes eachDouble. - 3Average. 78.0 / 4 = 19.5; divide by
size(), not a fixed number.
get and size().An empty list has no element 0, so list.get(0) throws an IndexOutOfBoundsException, and dividing a sum by list.size() divides by zero. When a list might be empty, check list.size() > 0 before computing a minimum, maximum, or average.
2Checking Properties
Three closely related algorithms test elements against a condition. To determine whether at least one element has a property, return true as soon as one is found, and return false only after the loop finishes. To determine whether all elements have it, return false at the first element that fails, and true after the loop. To find how many elements have it, count matches through the whole list.
The most common mistake is returning from the loop too soon: an "all" check that returns true inside the loop after one passing element has not looked at the rest. The answer that requires seeing every element always belongs after the loop.
At Least One, All, and How Many
Three methods ask three questions about the same list (Figure 1).
public static boolean atLeastOne(ArrayList<Integer> list, int min)
{
for (int v : list)
{
if (v >= min)
{
return true;
}
}
return false;
}
public static boolean allAtLeast(ArrayList<Integer> list, int min)
{
for (int v : list)
{
if (v < min)
{
return false;
}
}
return true;
}
public static int countAtLeast(ArrayList<Integer> list, int min)
{
int count = 0;
for (int v : list)
{
if (v >= min)
{
count++;
}
}
return count;
}
true
false
3
- 1At least one: return
trueat the first element that passes;falseonly after checking them all. - 2All: return
falseat the first element that fails;trueonly after checking them all. - 3How many: no early return; every passing element adds 1.
3Pairs and Duplicates
Accessing all consecutive pairs of elements compares each element with the next one: list.get(i) and list.get(i + 1). Because the last element has no next element, the loop runs while i < list.size() - 1. A list of five elements has four consecutive pairs. Pair algorithms find rises and falls, check whether a list is in order, or find the largest jump between neighbors.
Determining the presence or absence of duplicate elements compares each element with every element after it, using nested loops in which the inner index starts at i + 1. Starting there means no element is compared with itself and each pair is checked only once. String elements are compared with equals.
get(i) with get(i + 1), so the index stops one before the last element.Counting the Rises
Count how many times a value is larger than the one before it.
ArrayList<Integer> steps = new ArrayList<Integer>();
steps.add(3);
steps.add(5);
steps.add(4);
steps.add(8);
steps.add(9);
int rises = 0;
for (int i = 0; i < steps.size() - 1; i++)
{
if (steps.get(i + 1) > steps.get(i))
{
rises++;
}
}
System.out.println(rises);
3
- 1Bounds.
istops atsize() - 2, soget(i + 1)is always valid. - 2Pairs. 3→5 rises, 5→4 falls, 4→8 rises, 8→9 rises.
get(i) and get(i + 1) with a loop that ends one element early.Is Any Value Repeated?
Compare every element with every element after it.
ArrayList<String> stops = new ArrayList<String>();
stops.add("LHR");
stops.add("SFO");
stops.add("ICN");
stops.add("SFO");
boolean repeated = false;
for (int i = 0; i < stops.size(); i++)
{
for (int j = i + 1; j < stops.size(); j++)
{
if (stops.get(i).equals(stops.get(j)))
{
repeated = true;
System.out.println("repeat: " + stops.get(j) + " at " + i + " and " + j);
}
}
}
System.out.println(repeated);
repeat: SFO at 1 and 3
true
- 1Inner loop starts at
i + 1, so each pair is compared once and no element is compared with itself. - 2
equalscompares the text of two strings.
With i < list.size(), the final pass calls list.get(list.size()) through get(i + 1) and throws an IndexOutOfBoundsException. Pair loops end at list.size() - 1.
Elements of an ArrayList<Integer> are references, and == on two references asks whether they are the same object, not whether they hold the same number. Store the elements in int variables first, for example int a = list.get(i);, and compare those. Relational operators such as < and > unbox automatically.
4Shifting, Rotating, and Reversing
Because an ArrayList shifts elements itself, rotating is short. To rotate right by one, remove the last element and insert it at index 0; to rotate left by one, remove the element at index 0 and append it with add. Shifting without wrapping around works the same way, except the removed element is discarded and, if the size must stay the same, a placeholder value is added at the other end.
Reversing the order of the elements swaps pairs from the outside in: index 0 with the last index, index 1 with the second-to-last, and so on, for i < list.size() / 2. Each swap uses a temporary variable with get and set. Since set never changes the size, the loop bound stays correct throughout.
ArrayList, rotating right removes the last element and inserts it at index 0; add shifts the others automatically.Rotate Right, Then Left
Use remove and add to rotate the list (Figure 3).
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(10);
nums.add(20);
nums.add(30);
nums.add(40);
nums.add(50);
int last = nums.remove(nums.size() - 1);
nums.add(0, last);
System.out.println(nums);
int first = nums.remove(0);
nums.add(first);
System.out.println(nums);
[50, 10, 20, 30, 40]
[10, 20, 30, 40, 50]
- 1Right by one. Remove the last element and insert it at index 0;
add(0, ...)shifts everything else right. - 2Left by one. Remove the first element and append it;
remove(0)shifts everything else left. - 3No temporary array is needed, because the list moves elements itself.
Swapping From Both Ends With set
Predict the output.
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(12);
nums.add(7);
nums.add(19);
nums.add(4);
nums.add(15);
for (int i = 0; i < nums.size() / 2; i++)
{
int j = nums.size() - 1 - i;
int temp = nums.get(i);
nums.set(i, nums.get(j));
nums.set(j, temp);
}
System.out.println(nums);
[15, 4, 19, 7, 12]
- 1Pairs from the outside in. Index 0 swaps with 4, and 1 with 3; the middle element stays.
- 2
setkeeps the size the same, so the loop boundsize() / 2is stable.
get and set, using a temporary variable.| Task | Array version | ArrayList version |
|---|---|---|
| Insert at index k | Make room by shifting elements right by hand; length cannot grow | list.add(k, value) |
| Delete at index k | Shift elements left by hand; a leftover slot remains | list.remove(k) |
| Rotate right by one | Save the last element, shift the rest, store it at 0 | list.add(0, list.remove(list.size() - 1)) |
| Reverse | Swap with a temporary variable | Swap with get, set, and a temporary variable |
5Inserting and Deleting
Inserting an element at a particular position uses add(index, value). Keeping a list in order first finds the position, the index of the first element larger than the new value, then inserts there. The search loop must test pos < list.size() before list.get(pos), so that a value larger than every element stops at the end and is appended instead of causing an exception.
Deleting elements that meet a condition calls remove(i) for each match. To avoid skipping the element that slides into a removed position, traverse backward, or advance the index only when nothing was removed. Inserting during a forward traversal has the reverse problem: the inserted element is visited again on the next pass, so the index must move past it.
| pos | list.get(pos) | get(pos) < 17? | Action |
|---|---|---|---|
| 0 | 5 | true | pos becomes 1 |
| 1 | 12 | true | pos becomes 2 |
| 2 | 20 | false | loop ends |
| — | — | — | add(2, 17) → [5, 12, 17, 20, 31] |
Keeping a List in Order
Insert each value at the position that keeps the list sorted.
public static void insertInOrder(ArrayList<Integer> list, int value)
{
int pos = 0;
while (pos < list.size() && list.get(pos) < value)
{
pos++;
}
list.add(pos, value);
}
[2, 5, 12, 17, 20, 31, 40]
- 1Find the position. Move
pospast every element smaller than the new value (trace below). - 2The bounds check comes first. For 40,
posreachessize(); short-circuit&&stops beforeget(pos)would fail, andadd(size(), 40)appends. - 3For 2, the loop never runs and the value goes to index 0.
add(index, value).Removing Every Negative Reading
Delete all negative values without skipping any.
ArrayList<Integer> readings = new ArrayList<Integer>();
readings.add(4);
readings.add(-1);
readings.add(-1);
readings.add(7);
readings.add(0);
readings.add(-1);
readings.add(9);
for (int i = readings.size() - 1; i >= 0; i--)
{
if (readings.get(i) < 0)
{
readings.remove(i);
}
}
System.out.println(readings);
[4, 7, 0, 9]
- 1Backward traversal. Removing at
ishifts only elements that were already checked. - 2Adjacent matches (the two −1 values at indices 1 and 2) are both removed.
6Traversing Several Collections at Once
Some algorithms require multiple String, array, or ArrayList objects to be traversed simultaneously. When the collections line up position by position, one index serves them all: code.substring(i, i + 1) and guess.get(i) refer to the same position. Other algorithms copy elements from one collection into another, or keep a separate index for each collection.
The loop bound must be valid for every collection being traversed. If the lengths might differ, loop to the smaller length, or the shorter collection will be read past its end. Writing out the index and the elements from each collection on each pass is the clearest way to trace these algorithms.
String, an array, or an ArrayList simultaneously, using one index for all of them.Comparing a Code With a Guess
A String and an ArrayList are traversed together (Figure 4).
String code = "RGBY";
ArrayList<String> guess = new ArrayList<String>();
guess.add("R");
guess.add("B");
guess.add("B");
guess.add("Y");
int exact = 0;
for (int i = 0; i < guess.size(); i++)
{
if (code.substring(i, i + 1).equals(guess.get(i)))
{
exact++;
}
}
System.out.println(exact + " of " + code.length());
3 of 4
- 1One index, two collections.
iselects a one-letter substring ofcodeand the element ofguessat the same position. - 2Matches. Positions 0, 2, and 3 agree; position 1 ("G" versus "B") does not.
A loop bounded by one collection's size can run past the end of another. Before traversing two collections together, confirm their lengths match or loop to the smaller of the two.
Four Habits for List Algorithms
1. Start From a Real Element
get(0) for minimum and maximum.
2. Decide After the Loop
"All" and "none" need every element.
3. Let the List Shift
add and remove move elements for you.
4. Check Every Bound
Pairs stop early; paired collections share a valid bound.
There are standard ArrayList algorithms that utilize traversals to determine a minimum or maximum value; compute a sum or average; determine if at least one element has a particular property; determine if all elements have a particular property; determine the number of elements having a particular property; access all consecutive pairs of elements; determine the presence or absence of duplicate elements; shift or rotate elements left or right; reverse the order of the elements; insert elements; and delete elements. Some algorithms require multiple String, array, or ArrayList objects to be traversed simultaneously.