Standard Algorithms on ArrayList
Part of: ArrayList
Library of Patterns. The AP CSA exam expects you to write common list algorithms by hand on an ArrayList. These all build from get, set, size, and loops. Master these patterns. Finding a Maximum or Minimum. Assume the first element is the best, then improve: Searching. A linear search returns the index of a target, or -1 if absent: For objects like Strings, use .equals() instead of ==. Counting and Summing. Building a New List. Many problems filter or transform into a fresh list rather than mutating the original: Detecting Duplicates. A nested loop compares each pair: What usually goes wrong. What you see What caused it How to fix it --- --- --- The maximum comes back as 0 on an all-negative list The running max was seeded with 0 rather than a real element Seed with list.get(0) IndexOutOfBoundsException on the seeding line itself get(0) was called on an empty list Guard with if (list.size() 0) when the list can be empty The reported index points at a later duplicate of the max = was used, so a tie overwrote the earlier winner Use so only a strictly larger value replaces the best so far Summary. - Max/min: seed with the first element, then compare. - Linear search: return index or -
Challenge: Find Max and Its Index