Unit 4 Day 16 Arraylist Algorithms
Share
Unit 4: Data Collections
Day 16 PracticeMedium
Focus: Common ArrayList operations
Today's Question
What does the following method return for the list [3, 1, 4, 1, 5]?
class="apcs-keyword">public static int process(ArrayList<Integer> list) {
int result = 0;
for (int num : list) {
if (num > result) {
result = num;
}
}
return result;
}
This method finds the maximum value in the list. It starts with result=0, then updates result whenever it finds a larger value. The maximum in [3,1,4,1,5] is 5.
Key Concept
Finding the maximum uses an accumulator pattern: start with a minimum value and update when you find something larger.