dev only
Implementing ArrayList Algorithms
Every pattern from Lesson 9.5 (sum/average, min/max, search, property checks, duplicates, reversing) applies to ArrayList too — just swap [i]/.length for get(i)/.size().
Min / Max / Average
public static double average(ArrayList<Double> nums)
{
double sum = 0;
for (int i = 0; i < nums.size(); i++)
{
sum += nums.get(i);
}
return sum / nums.size();
}
Duplicates — Use .equals(), Not ==
For ArrayList<Integer> (or any object type), comparing with == checks identity, not value — use .equals() instead:
for (int i = 0; i < nums.size(); i++)
{
for (int j = i + 1; j < nums.size(); j++)
{
if (nums.get(i).equals(nums.get(j))) // .equals(), not ==
{
return true;
}
}
}
Rotating (In Place, with get/set)
public static void rotateRight(ArrayList<Double> nums)
{
double last = nums.get(nums.size() - 1);
for (int i = nums.size() - 1; i > 0; i--)
{
nums.set(i, nums.get(i - 1));
}
nums.set(0, last);
}
Parallel ArrayLists
Same idea as parallel arrays (Ch.9.1) — two lists kept in sync by index:
ArrayList<String> autoNames = new ArrayList<String>();
ArrayList<Double> autoTimes = new ArrayList<Double>();
// autoTimes.get(i) is the recorded time for autoNames.get(i)
Common Pitfalls
- Comparing objects with
==instead of.equals(). This is the single most common ArrayList-specific mistake —nums.get(i) == nums.get(j)checks whether they're the same object, which is unreliable even for boxedIntegers. - Using array syntax (
[]) out of habit.nums[i]doesn't compile on anArrayList— it's alwaysget/set. - Forgetting
.size()changes as you add/remove. A loop bound computed once before a series of removals can end up stale.
Key Takeaways
- Every array algorithm pattern (accumulator, min/max, search, property checks, duplicates, rotate, reverse) transfers directly to
ArrayList— just swap[i]/.lengthforget(i)/.size(). - Compare
ArrayListelements with.equals(), not==, when the element type is an object (including boxed numbers likeInteger). - Parallel
ArrayLists keep related data in sync by index, same as parallel arrays.
Derived from csawesome-2026: unit-4-data-collections/4.10-implementing-arraylist-algorithms.md (CSA 4.10)