ArrayList Traversals

Help Questions

AP Computer Science A › ArrayList Traversals

Questions 1 - 10
1

What is the purpose of the loop in the provided code?


// Part A: Setup

ArrayList<Double> prices = new ArrayList<>();

prices.add(2.5);

prices.add(null);

prices.add(1.0);

// Part B: Sum values safely

double totalSum = 0.0;

for (Double price : prices) { // traverse list

    if (price != null) {

        totalSum += price; // add non-null values

    }

}

// Part C: Output

System.out.println(totalSum);

To count how many null values exist

To sum all elements, including null as 0.0

To avoid a syntax error from using Double

To sum only non-null values in the list

Explanation

This question tests AP Computer Science A skills in ArrayList traversal, specifically handling null values safely during iteration. ArrayLists can contain null references, and attempting operations on null values can cause NullPointerException. In this code snippet, the enhanced for loop traverses the list containing [2.5, null, 1.0], and the null check prevents adding null to the sum. The purpose is to calculate the sum of only non-null values: 2.5 + 1.0 = 3.5. Choice C is correct because the code explicitly checks for null before adding to the sum, ensuring only valid Double values are processed. Choice B is incorrect because null is not treated as 0.0; it's completely skipped. To help students: Emphasize the importance of null checks when working with object types in collections. Practice identifying potential NullPointerException scenarios. Watch for: Forgetting that wrapper classes (Double, Integer) can be null, unlike primitives.

2

How does the code modify the ArrayList?


// Part A: Setup

ArrayList<Integer> scores = new ArrayList<>();

scores.add(5);

scores.add(12);

scores.add(10);

// Part B: Conditional modification

for (int i = 0; i < scores.size(); i++) { // traverse by index

    if (scores.get(i) > 10) {

        scores.set(i, scores.get(i) * 2); // update element

    }

}

// Part C: Output

System.out.println(scores);

It causes a type mismatch at set()

It doubles values greater than 10 only

It removes values greater than 10 only

It doubles every element in the list

Explanation

This question tests AP Computer Science A skills in ArrayList traversal, specifically understanding indexed traversal and conditional modification of elements. ArrayLists allow modification during traversal using the set() method, which replaces an element at a specific index. In this code snippet, the loop uses index-based traversal to check each element and doubles only those greater than 10. The ArrayList starts with [5, 12, 10], and only the value 12 (at index 1) is greater than 10, so it becomes 24. Choice B is correct because the code doubles only values strictly greater than 10, resulting in [5, 24, 10]. Choice A is incorrect because it suggests all elements are doubled, missing the conditional check. To help students: Trace through each iteration carefully, noting which conditions are met. Practice distinguishing between > and >= operators. Watch for: Confusing greater than (>) with greater than or equal to (>=), misunderstanding how set() works.

3

What will be the output of the given code snippet?


// Part A: Setup

ArrayList<String> words = new ArrayList<>();

words.add("Hi");

words.add("hi");

words.add("HI");

// Part B: Count occurrences (case-sensitive)

int count = 0;

for (String w : words) { // traverse list

    if (w.equals("hi")) {

        count++;

    }

}

// Part C: Output

System.out.println(count);

0

1

2

3

Explanation

This question tests AP Computer Science A skills in ArrayList traversal, specifically understanding case-sensitive string comparison. The equals() method in Java performs case-sensitive comparison, meaning "Hi", "hi", and "HI" are all different strings. In this code snippet, the enhanced for loop traverses the list and counts occurrences of exactly "hi" (lowercase). Only the second element matches this exact string. Choice B is correct because only one element in the list equals "hi" with exact case matching. Choice D is incorrect because it would require case-insensitive comparison or counting all variations. To help students: Demonstrate the difference between equals() and equalsIgnoreCase(). Practice with various string comparison scenarios. Watch for: Assuming string comparison is case-insensitive by default, confusing equality with similarity.

4

What will be the output of the given code snippet?


// Part A: Setup

ArrayList<Integer> numbers = new ArrayList<>();

// Part B: Find maximum

int maxValue = Integer.MIN_VALUE;

for (int value : numbers) { // traverse list

    if (value > maxValue) {

        maxValue = value;

    }

}

// Part C: Handle empty list

if (numbers.size() == 0) {

    System.out.println("empty");

} else {

    System.out.println(maxValue);

}

Prints empty

Causes a syntax error

Prints -2147483648

Prints 0

Explanation

This question tests AP Computer Science A skills in ArrayList traversal, specifically understanding how to handle empty lists and find maximum values. ArrayLists in Java are dynamic arrays that can be empty, and traversing an empty list requires careful handling to avoid errors. In this code snippet, the ArrayList 'numbers' is created but no elements are added, making it empty. The enhanced for loop attempts to traverse the list, but since it's empty, the loop body never executes, leaving maxValue at Integer.MIN_VALUE. Choice A is correct because the code checks if the list size is 0 (which it is) and prints "empty" accordingly. Choice C is incorrect because while maxValue remains Integer.MIN_VALUE (-2147483648), the conditional statement prevents this value from being printed. To help students: Emphasize the importance of checking for empty collections before processing. Practice tracing code with edge cases like empty lists. Watch for: Assuming loops always execute at least once, forgetting to handle empty collection scenarios.

5

How does the code modify the ArrayList?


// Part A: Setup

ArrayList<Integer> data = new ArrayList<>();

data.add(11);

data.add(10);

data.add(15);

// Part B: Conditional modification

for (int i = 0; i < data.size(); i++) { // traverse list

    int current = data.get(i);

    if (current > 10) {

        data.set(i, current * 2); // replace element

    }

}

// Part C: Output

System.out.println(data);

It doubles only the first value greater than 10

It doubles values greater than 10 only

It causes an off-by-one error and skips 15

It doubles values greater than or equal to 10

Explanation

This question tests AP Computer Science A skills in ArrayList traversal, specifically understanding conditional modification with the greater than operator. The code uses index-based traversal to check each element and doubles those strictly greater than 10. In this ArrayList containing [11, 10, 15], the values 11 and 15 are greater than 10, while 10 itself is not (since the condition uses > not >=). After modification, the list becomes [22, 10, 30]. Choice A is correct because the code doubles only values strictly greater than 10, leaving 10 unchanged. Choice B is incorrect because it suggests >= behavior when the code uses > operator. To help students: Carefully distinguish between > and >= operators in conditions. Trace through each element to see which meet the condition. Watch for: Misreading comparison operators, assuming boundary values are included when they're not.

6

How does the code modify the ArrayList?


// Part A: Setup

ArrayList<Integer> values = new ArrayList<>();

values.add(3);

values.add(-1);

values.add(-2);

values.add(4);

// Part B: Remove negatives (backwards)

for (int i = values.size() - 1; i >= 0; i--) { // traverse safely

    if (values.get(i) < 0) {

        values.remove(i); // remove negative

    }

}

// Part C: Output

System.out.println(values);

It removes only the first negative number found

It removes all negative numbers from the list

It skips removals due to shifting indices

It causes a syntax error in the for loop

Explanation

This question tests AP Computer Science A skills in ArrayList traversal, specifically understanding safe element removal during iteration. When removing elements from an ArrayList during traversal, iterating backwards prevents index shifting issues. In this code snippet, the loop starts from the last index and moves backwards, removing elements with negative values (-1 and -2). This approach ensures all negative numbers are removed without skipping any due to index shifts. Choice A is correct because the backwards traversal successfully removes all negative numbers, leaving [3, 4]. Choice C is incorrect because backwards traversal specifically avoids the index shifting problem. To help students: Visualize how removing elements shifts subsequent indices. Practice both forward and backward traversal for removal operations. Watch for: Attempting to remove elements while traversing forward with a regular for loop, which causes elements to be skipped.

7

Which line contains an error affecting traversal?


// Part A: Setup

ArrayList<Integer> numbers = new ArrayList<>();

numbers.add(7);

numbers.add(2);

// Part B: Find maximum

int maxValue = numbers.get(0);

for (int i = 0; i <= numbers.size(); i++) { // traverse

    if (numbers.get(i) > maxValue) {

        maxValue = numbers.get(i);

    }

}

// Part C: Output

System.out.println(maxValue);

Line with numbers.add(2);

Line with int maxValue = numbers.get(0);

Line with for (int i = 0; i <= numbers.size(); i++)

Line with System.out.println(maxValue);

Explanation

This question tests AP Computer Science A skills in ArrayList traversal, specifically identifying off-by-one errors in loop conditions. ArrayLists are zero-indexed, with valid indices from 0 to size()-1. In this code snippet, the loop condition uses i <= numbers.size(), which will attempt to access index 2 when the list only has indices 0 and 1. This causes an IndexOutOfBoundsException when the loop tries to access numbers.get(2). Choice C is correct because the loop condition should use i < numbers.size() instead of i <= numbers.size() to avoid accessing an invalid index. Choice B is incorrect because accessing the first element with get(0) is valid when the list is not empty. To help students: Emphasize that ArrayList indices range from 0 to size()-1. Practice identifying boundary conditions in loops. Watch for: Using <= with size() in loop conditions, forgetting that collections are zero-indexed.

8

What will be the output of the given code snippet?


// Part A: Setup

ArrayList<Double> readings = new ArrayList<>();

readings.add(1.5);

readings.add(null);

readings.add(2.0);

// Part B: Sum values safely

double totalSum = 0.0;

for (int i = 0; i < readings.size(); i++) { // traverse by index

    Double r = readings.get(i);

    if (r != null) {

        totalSum += r;

    }

}

// Part C: Output

System.out.println(totalSum);

Causes a type mismatch error

0.0

3.5

null

Explanation

This question tests AP Computer Science A skills in ArrayList traversal, specifically understanding index-based iteration with null handling. This code demonstrates safe summation of Double values in an ArrayList that contains null. The loop uses index-based traversal to access each element, storing it in a Double variable before checking for null. The sum includes 1.5 and 2.0, while null is skipped, resulting in 3.5. Choice A is correct because the code successfully sums the non-null values (1.5 + 2.0 = 3.5). Choice B is incorrect because the code doesn't return null; it calculates and prints a numeric sum. To help students: Show how both enhanced for loops and index-based loops can handle null checking. Practice working with wrapper classes that can hold null values. Watch for: Assuming primitive types can be null, forgetting to check for null before arithmetic operations.

9

What is the purpose of the loop in the provided code?


// Part A: Setup

ArrayList<String> names = new ArrayList<>();

names.add("Alex");

names.add("alex");

names.add("ALEX");

// Part B: Count occurrences (ignore case)

int count = 0;

for (String name : names) { // traverse list

    if (name.equalsIgnoreCase("alex")) {

        count++;

    }

}

// Part C: Output

System.out.println(count);

To count only exact-case matches of "alex"

To count matches of "alex" regardless of case

To sort the list before counting

To remove names that do not match "alex"

Explanation

This question tests AP Computer Science A skills in ArrayList traversal, specifically understanding case-insensitive string comparison. The equalsIgnoreCase() method compares strings without considering case differences, treating "Alex", "alex", and "ALEX" as equal. In this code snippet, the enhanced for loop traverses the list and counts all variations of "alex" regardless of case. All three elements in the list match when case is ignored. Choice B is correct because the code counts all occurrences of "alex" in any case combination, resulting in a count of 3. Choice A is incorrect because equalsIgnoreCase() specifically ignores case differences. To help students: Compare equals() and equalsIgnoreCase() side by side. Practice with various string methods that handle case. Watch for: Confusing case-sensitive and case-insensitive comparison methods, misunderstanding the purpose of equalsIgnoreCase().

10

What will be the output of the given code snippet?


// Part A: Setup

ArrayList<Integer> numbers = new ArrayList<>();

numbers.add(4);

numbers.add(9);

numbers.add(1);

// Part B: Find maximum

int maxValue = Integer.MIN_VALUE;

for (int value : numbers) { // traverse list

    if (value > maxValue) {

        maxValue = value;

    }

}

// Part C: Output

System.out.println(maxValue);

Causes a syntax error in the loop

1

9

4

Explanation

This question tests AP Computer Science A skills in ArrayList traversal, specifically finding the maximum value using an enhanced for loop. The code initializes maxValue to Integer.MIN_VALUE (the smallest possible integer) to ensure any actual value in the list will be larger. The enhanced for loop traverses the ArrayList containing [4, 9, 1], comparing each value to maxValue and updating it when a larger value is found. The maximum value in the list is 9. Choice C is correct because the algorithm successfully identifies 9 as the largest value among 4, 9, and 1. Choice A is incorrect because it's the minimum value in the list, not the maximum. To help students: Trace through the algorithm step by step, showing how maxValue changes. Practice with different initial values for finding min/max. Watch for: Confusing minimum and maximum finding algorithms, misunderstanding the purpose of Integer.MIN_VALUE as initial value.