Unit 4 Cycle 1 Day 14: ArrayList: Building from Array
Share
ArrayList: Building from Array
Section 4.5 — ArrayList Algorithms
Key Concept
Converting between arrays and ArrayList is a common AP exam operation. To build an ArrayList from an array, iterate through the array and add() each element. For an int[], autoboxing converts each int to Integer. To convert an ArrayList to an array, use a loop or toArray(). The AP exam tests this conversion pattern in methods that receive one type and return the other, requiring you to translate between indexed access and list methods.
Consider the following code segment.
What is printed?
Answer: (A) [8]
Check each: 5%2=1(odd), 3%2=1(odd), 8%2=0(even, add), 1%2=1(odd), 9%2=1(odd). Only 8 is even. Result: [8].
Why Not the Others?
(B) This lists the odd numbers, not the even ones.
(C) 5 is odd (5%2=1). Only 8 is even.
(D) 8 is even and is added to the list.
Common Mistake
val % 2 == 0 checks for even numbers. Filtering elements from an array into an ArrayList is a common pattern. The ArrayList grows dynamically.
AP Exam Tip
ArrayList is preferred over arrays when you do not know the final size in advance. Filtering (selecting elements that meet a condition) naturally uses ArrayList.