AP CSA 4.9 Exercise 1: Removing While You Walk

Unit 4: Data Collections · Lesson 4.9 · Exercise 1

Removing While You Walk

Traversing ArrayLists. Write real Java, run it, and submit it to be graded against hidden test cases.

Why this one is worth doing

Removing an element during a forward traversal makes the loop skip the next one, which is the classic ArrayList bug and is on the exam. Doing it backwards avoids the problem entirely, and this exercise asks for both so the difference is visible in the output.

What to write

  1. Read an integer count, then that many integers into an ArrayList of Integer.
  2. Print the sum using an enhanced for loop.
  3. Make a copy of the list. Walk the copy FORWARDS with an index and remove every even value, without adjusting the index after a removal. Print the result, bug and all.
  4. Make another copy. Walk it BACKWARDS and remove every even value. Print that result.
  5. Print true when the two results are equal and false when the forward version missed something.

Your program reads

An integer count of at least 1, then that many integers.

Your program prints

The sum, the forward result, the backward result and whether they matched.

Worked examples

These are the cases you can see. There are more you cannot, and they use different values, so an answer that prints these numbers as constants will fail.

Example 1 input
6
1 2 4 3 6 5
Example 1 output
21
[1, 4, 3, 5]
[1, 3, 5]
false
Example 2 input
4
1 3 5 7
Example 2 output
16
[1, 3, 5, 7]
[1, 3, 5, 7]
true

Your answer

Main.java

Input for the Run button

Run sends whatever is in the input box below. Submitting runs your program against every test case, including hidden ones with different input.


  

  

Stuck?

Hint 1

After remove(i) everything shifts left, so the element that moved into position i never gets tested. Two evens in a row is where it shows.

Hint 2

The backward loop is immune because everything that shifts has already been visited.

Hint 3

Comparing two ArrayLists with equals compares their contents in order, which is what the last line wants.

Where to go next

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]