ArrayList Practice Worksheet - Insert and Remove Operations
ArrayList Practice Worksheet - Insert and Remove Operations
For each question, show what the ArrayList contains after performing all the given operations in order. Write out each step to get full credit.
Question 1
Start with an empty ArrayList
words.add("cat")
words.add("dog")
words.add(1, "bird")
words.remove(0)
words.add("fish")
words.remove("bird")
Show the final contents of the ArrayList:
Final answer: [______, ______]
Question 2
Start with an ArrayList
nums.add(2, 12)
nums.remove(Integer.valueOf(10))
nums.add(0, 3)
nums.remove(nums.size()-1)
nums.add(nums.get(1))
Show the final contents of the ArrayList:
Final answer: [______, ______, ______, ______, ______]
Question 3
Start with an ArrayList
colors.add("yellow")
colors.set(1, "purple")
colors.remove(2)
colors.add(1, "orange")
colors.remove("red")
colors.add(colors.get(0))
Show the final contents of the ArrayList:
Final answer: [______, ______, ______, ______]
Question 4
Start with an ArrayList
nums.add(3)
- For loop that runs forward through the list:
for(int i = 0; i < nums.size(); i++) { if(nums.get(i) % 4 == 0) { nums.remove(i); } }
nums.add(0, 1)
- For loop that doubles each number:
for(int i = 0; i < nums.size(); i++) { nums.set(i, nums.get(i) * 2); }
Show the final contents of the ArrayList:
Final answer: [______, ______, ______, ______, ______, ______]