AP Computer Science A · Topic 7.4
Developing Algorithms Using ArrayLists Practice
Part of ArrayList.
Practice questions
31
Sample questions
5 of 31 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
ArrayList<Integer> a = new ArrayList<>(); a.add(1); a.add(2); a.add(3); ArrayList<Integer> b = new ArrayList<>(); for (int x : a) b.add(x * 2); System.out.println(b);What is printed?
- Acheck_circle
[2, 4, 6]
- B
[1, 2, 3]
- C
[1, 4, 9]
- D
[]
Why
Each element of a is doubled and added to b: 1<em>2=2, 2</em>2=4, 3*2=6.
- A
Sample 2difficulty 2/5
int[] arr = {3, 1, 4, 1, 5}; ArrayList<Integer> list = new ArrayList<>(); for (int x : arr) list.add(x); System.out.println(list.size());What is printed?
- A
0
- B
4
- C
3
- Dcheck_circle
5
Why
Each of the 5 elements is added to the list, so size is 5.
- A
Sample 3difficulty 2/5
ArrayList<Integer> list = new ArrayList<>(); list.add(5); list.add(2); list.add(5); list.add(7); list.add(5); list.add(2); int count = 0; for (int x : list) { if (x == 5) count++; } System.out.println(count);What is printed?
- A
2
- B
4
- C
0
- Dcheck_circle
3
Why
The value 5 appears at indices 0, 2, and 4. Count = 3.
- A
Sample 4difficulty 3/5
ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); for (int i = 0; i < list.size(); i++) { if (list.get(i) % 2 == 0) { list.remove(i); } }What is list after the loop?
- A
[2, 4]
- Bcheck_circle
[1, 3]
- C
[1, 3, 4]
- D
[1, 2, 3, 4]
Why
Removing while incrementing skips elements; here both 2 and 4 happen to get removed correctly only with care, leaving [1,3].
- A
Sample 5difficulty 3/5
ArrayList<Integer> list = new ArrayList<>(); list.add(2); list.add(2); list.add(3); list.add(4); for (int i = 0; i < list.size(); i++) { if (list.get(i) == 2) { list.remove(i); } }What does list contain?
- A
[]
- B
[3, 4]
- C
[2, 2, 3, 4]
- Dcheck_circle
[2, 3, 4]
Why
After removing index 0, the second 2 shifts to index 0 but i becomes 1, skipping it.
- A