Unit 4 Cycle 1 Day 14: ArrayList: Building from Array

Unit 4 Foundation (Cycle 1) Day 14 of 28 Foundation

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.

int[] arr = {5, 3, 8, 1, 9}; ArrayList evens = new ArrayList(); for (int val : arr) { if (val % 2 == 0) { evens.add(val); } } System.out.println(evens);

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.

Review this topic: Section 4.5 — ArrayList Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.