AP Computer Science A · Topic 7.1
Introduction to ArrayList Practice
Part of ArrayList.
Practice questions
15
Sample questions
5 of 15 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
ArrayList<Integer> list = new ArrayList<>(); list.add(7); list.add(8); int x = list.get(0) + list.get(1); System.out.println(x);What is printed?
- A
Compile-time error
- B
7
- Ccheck_circle
15
- D
78
Why
Autoboxing converts int 7 and 8 into Integer objects when added. Auto-unboxing converts them back to int when adding, producing 15.
- A
Sample 2difficulty 2/5
ArrayList<Integer> list = new ArrayList<>(); int sum = 0; for (int x : list) sum += x; System.out.println(sum + " " + list.size());What is printed?
- A
Runtime error
- B
0 1
- C
1 0
- Dcheck_circle
0 0
Why
The list is empty so the for-each loop never executes, sum stays 0, and size is 0.
- A
Sample 3difficulty 2/5
ArrayList<Integer> list = new ArrayList<>(); for (int i = 1; i <= 5; i++) list.add(i); int s = 0; for (int x : list) s += x; System.out.println(s);What is printed?
- A
Compile-time error
- B
5
- C
10
- Dcheck_circle
15
Why
The loop adds 1, 2, 3, 4, 5 to the list. Summing them with the for-each loop gives 1+2+3+4+5 = 15. Autoboxing converts each int to an Integer when adding.
- A
Sample 4difficulty 2/5
Which is a correct ArrayList declaration?
- A
ArrayList list = new ArrayList(int);
- Bcheck_circle
ArrayList<Integer> list = new ArrayList<>();
- C
ArrayList<int> list = new ArrayList<int>();
- D
ArrayList<int> list = new ArrayList<>();
Why
Generic type parameter must be a reference type; use <code>Integer</code> (not <code>int</code>).
- A
Sample 5difficulty 3/5
<code>ArrayList<int></code> is
- Acheck_circle
Compile error (can only use reference types)
- B
Valid (will autobox)
- C
Slow but works
- D
Compiles only with --enable-experimental
Why
Generic type parameters must be reference types; use Integer, Double, etc.
- A