AP CSA 4.8 Exercise 1: Add, Set, Remove

Unit 4: Data Collections · Lesson 4.8 · Exercise 1

Add, Set, Remove

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

Why this one is worth doing

add with an index shifts everything right and remove shifts everything left, while set changes one slot and moves nothing. Three methods that look similar and do genuinely different things to the positions around them.

What to write

  1. Read an integer count, then that many integers, and put them in an ArrayList of Integer.
  2. Print the list.
  3. Add the value 99 at index 1, then print the list.
  4. Set index 0 to the value 0, then print the list.
  5. Remove the element at index 2 and print what remove returned, then print the list.
  6. Print the size on the last line. Print a list as its default Java form, for example [1, 2, 3].

Your program reads

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

Your program prints

The list four times as the operations are applied, the removed value, and finally the size.

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
4
10 20 30 40
Example 1 output
[10, 20, 30, 40]
[10, 99, 20, 30, 40]
[0, 99, 20, 30, 40]
20
[0, 99, 30, 40]
4
Example 2 input
3
1 2 3
Example 2 output
[1, 2, 3]
[1, 99, 2, 3]
[0, 99, 2, 3]
2
[0, 99, 3]
3

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

add(1, 99) inserts and pushes everything from index 1 onward one place to the right. The list gets longer.

Hint 2

set(0, 0) replaces what is already there. The list stays the same length.

Hint 3

remove(int index) hands back the element it took out, so you can print the return value directly.

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]