Unit 4 Cycle 2 Day 26: Mixed: 2D Array to ArrayList

Unit 4 Advanced (Cycle 2) Day 26 of 28 Advanced

Mixed: 2D Array to ArrayList

Section Mixed — Review: All Unit 4

Key Concept

Converting between 2D arrays and ArrayList combines both data structure skills. Extracting a column from a 2D array into an ArrayList requires iterating over rows and adding grid[r][targetCol]. Flattening a 2D array into a 1D ArrayList uses nested loops to add every element. The AP exam tests these conversions as part of larger algorithms that process 2D data using ArrayList methods like sorting or filtering that are not available for raw arrays.

Consider the following code segment.

int[][] grid = {{5, 3, 8}, {1, 9, 2}, {7, 4, 6}}; ArrayList above5 = new ArrayList(); for (int[] row : grid) for (int val : row) if (val > 5) above5.add(val); System.out.println(above5.size() + " " + above5.get(0));

What is printed?

Answer: (A) 4 8

Values > 5 (row-major): 8, 9, 7, 6. Size=4. First: 8.

Why Not the Others?

(B) Four values exceed 5, not three.

(C) 5 is NOT greater than 5.

(D) Both wrong.

Common Mistake

Filtering 2D array into ArrayList: traverse row-major, add matching elements. Order reflects traversal order.

AP Exam Tip

Combining 2D arrays with ArrayLists is a common AP exam pattern.

Review this topic: Section Mixed — Review: All Unit 4 • Unit 4 Study Guide
Back to blog

Leave a comment

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