AP® Computer Science A Data Collections Practice Questions
Work through AP Computer Science A practice questions on Data Collections, then check each answer against a worked solution.
Free · no sign-up Open questions need no account. Sign up or log in to open the rest.
Question 1152
A retail system models each item for sale as a Product and uses a Store object to hold every product currently tracked by the store. The two classes are shown below; only the method totalValueOfLowStock in Store is left for you to complete. Everything else is already written.
public class Product
{
private String name;
private double price;
private int quantity;
public Product(String theName, double thePrice, int theQuantity)
{
name = theName;
price = thePrice;
quantity = theQuantity;
}
public String getName() { return name; }
public double getPrice() { return price; }
public int getQuantity() { return quantity; }
}
public class Store
{
/** Inventory of products currently tracked by this store. Never null. */
private ArrayList<Product> inventory;
public Store(ArrayList<Product> startingInventory)
{
inventory = startingInventory;
}
/** Returns the total dollar value of all products in inventory whose current
* quantity is strictly less than threshold. The dollar value of a single
* product is its price multiplied by its quantity. If no product has a
* quantity below threshold, the method returns 0.0.
* @param threshold the cutoff quantity; assumed to be non-negative
* @return the sum of price * quantity over all low-stock products
*/
public double totalValueOfLowStock(int threshold) { /* to implement */ }
}
Write the method totalValueOfLowStock. The method must iterate over every product in inventory and accumulate the dollar value price * quantity for each product whose current quantity is strictly less than threshold.
Suppose inventory holds three products:
{name:"widget", price:4.50, quantity:2}, {name:"gizmo", price:10.00, quantity:7}, {name:"bolt", price:0.25, quantity:3}.
A call to totalValueOfLowStock(5) selects the "widget" (quantity 2) and the "bolt" (quantity 3) because 7 is not less than 5. The returned value is \(4.50 \times 2 + 0.25 \times 3 = 9.75\).
public double totalValueOfLowStock(int threshold)Main Solution
Sample Solution
public double totalValueOfLowStock(int threshold)
{
double total = 0.0;
for (int i = 0; i < inventory.size(); i++)
{
Product p = inventory.get(i);
if (p.getQuantity() < threshold)
{
total = total + p.getPrice() * p.getQuantity();
}
}
return total;
}
Scoring notes. Points are earned for: iterating over every index of inventory (a for or enhanced-for loop both work); retrieving each Product via get(i) and using its accessor methods rather than touching the private fields; comparing getQuantity() strictly to threshold; accumulating getPrice() * getQuantity() only for low-stock products; and returning the correct double total. Common errors include using a non-strict comparison (which includes products whose quantity equals threshold) or accessing inventory.get(i).price directly.
Answer images
Question 1153
A topographic survey is stored in a class HeightMap, which uses a two-dimensional array to hold the elevation of each grid cell. Row 0 is the northernmost row and column 0 is the westernmost column. All rows have the same length. The grid is at least \(1 \times 1\).
public class HeightMap
{
/** Elevation grid; heights[r][c] is the elevation of the cell at row r, column c.
* Guaranteed to be a rectangular, non-empty 2D array of integers. */
private int[][] heights;
public HeightMap(int[][] grid)
{
heights = grid;
}
/** Part: see below. */
public boolean[][] peaks() { /* to implement */ }
}
Write the method peaks. The method returns a newly constructed boolean array of the same dimensions as heights. Entry [r][c] in the returned array is true if and only if the elevation at cell (r, c) is strictly greater than the elevation of every one of its orthogonal neighbors that exists in the grid. The orthogonal neighbors of (r, c) are the cells directly north, south, west, and east: (r-1, c), (r+1, c), (r, c-1), and (r, c+1). Neighbors outside the grid are simply ignored when making the comparison.
A corner cell has only two neighbors; an edge cell has only three neighbors; an interior cell has four. A cell with any neighbor at or above its own elevation is not a peak. A cell in a \(1 \times 1\) grid has no neighbors and is therefore a peak.
Let heights be the grid
{ {1, 4, 2}, {3, 2, 5}, {1, 1, 2} }.
The call peaks() returns
{ {false, true, false}, {true, false, true}, {false, false, false} }.
Explanation: (0,1) = 4 beats its existing neighbors 1, 2, 2; (1,0) = 3 beats 1, 2, 1; (1,2) = 5 beats 2, 2, 2. Every other cell has at least one neighbor at least as tall as itself.
public boolean[][] peaks()
Open each "Show solution" accordion above to compare your response against the reference implementation and scoring notes.
Main Solution
Sample Solution
public boolean[][] peaks()
{
int rows = heights.length;
int cols = heights[0].length;
boolean[][] result = new boolean[rows][cols];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
boolean isPeak = true;
int value = heights[r][c];
if (r - 1 >= 0 && heights[r - 1][c] >= value)
{
isPeak = false;
}
if (r + 1 < rows && heights[r + 1][c] >= value)
{
isPeak = false;
}
if (c - 1 >= 0 && heights[r][c - 1] >= value)
{
isPeak = false;
}
if (c + 1 < cols && heights[r][c + 1] >= value)
{
isPeak = false;
}
result[r][c] = isPeak;
}
}
return result;
}
Scoring notes. Points are earned for: allocating a new boolean[rows][cols] of the correct shape; visiting every cell with a nested loop; correctly bounds-checking each of the four neighbors before indexing; using a strict comparison so that ties disqualify a peak; and returning the result array. Any attempt to access heights[-1][c], heights[rows][c], heights[r][-1], or heights[r][cols] without a guard earns zero for the traversal; so does an off-by-one that reports a tie as a peak. A correct solution for the 1×1 case (no neighbors, so the single cell is a peak) falls out of the isPeak = true initialization when every guard fails.
Answer images
Question 1154
Question 1155
Question 1156
int[][] g = { {1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12} };
int sum = 0;
for (int r = 0; r < g.length; r++)
{
for (int c = 0; c < g[0].length; c++)
{
if (r == c || c == g[0].length - 1 - r)
{
sum = sum + g[r][c];
}
}
}
System.out.println(sum);
What is printed when the code segment executes?Main Solution
Answer
Answer: D. The condition selects cells on either the main diagonal (r == c) or the anti-diagonal (c == cols - 1 - r). For a 3×4 grid (cols = 4), the main-diagonal cells are g[0][0] = 1, g[1][1] = 6, g[2][2] = 11, summing to 18. The anti-diagonal cells are g[0][3] = 4, g[1][2] = 7, g[2][1] = 10, summing to 21. No cell in this 3×4 grid satisfies both conditions, so the union sum is 18 + 21 = 39. Option A counts only the main diagonal; option B counts only the anti-diagonal; option C double-counts a cell that the student incorrectly believed lay on both diagonals.
Answer: Correct: D
A
18
B
21
C
46
D
39
Answer images
Question 1157
Question 1158
Question 1159
Question 1160
name,grade,present
Ali,87,true
Bea,72,false
Cyd,91,true
Dax,54,true
A program creates a properly constructed Scanner sc reading that file, then runs the following code. Assume any imports needed are present.
sc.nextLine();
int total = 0;
int n = 0;
while (sc.hasNext())
{
String line = sc.nextLine();
String[] parts = line.split(",");
if (parts[2].equals("true"))
{
total = total + Integer.parseInt(parts[1]);
n = n + 1;
}
}
sc.close();
double avg = total * 1.0 / n;
What is the value of avg when the segment finishes?Main Solution
Answer
Answer: A. The first sc.nextLine() consumes the header so it is never parsed — option D is wrong because the header is skipped before any parseInt is attempted. Each remaining line is split on commas. Records with parts[2].equals("true") are Ali (87), Cyd (91), and Dax (54); Bea is excluded. So total = 87 + 91 + 54 = 232 and n = 3. avg = 232 * 1.0 / 3 = 77.333…. Option B averages all four students.
Answer: Correct: A
A
77.33333333333333
B
76.0
C
87.0
D
A run-time exception is thrown when parsing the header.
Answer images
AP® and Advanced Placement® are registered trademarks of the College Board, which is not affiliated with, and does not endorse, Verityprep. Names are used for identification purposes only.

