Skip to the content.

Unit 7 Notes

Unit 7: ArrayList – AP Computer Science A

🔑 Key Concepts

  • Importing and declaring ArrayList
  • Common methods: add(), get(), set(), remove(), size()
  • Differences between arrays and ArrayList
  • Traversing an ArrayList with loops
  • Wrapper classes with ArrayList (no primitives allowed)

📥 Import and Declaration

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();
  • Can only hold objects (e.g. String, Integer, Double, etc.)
  • No primitives allowed — use wrapper classes like Integer for int

⚙️ Common Methods

names.add("Alice");       // adds to end
names.add(0, "Bob");      // adds at index 0
names.get(1);             // gets item at index 1
names.set(1, "Charlie");  // replaces item at index 1
names.remove(0);          // removes item at index 0
names.size();             // returns number of elements

🔁 Traversing an ArrayList

Using for loop:

for (int i = 0; i < names.size(); i++) {
    System.out.println(names.get(i));
}

Using enhanced for-loop:

for (String name : names) {
    System.out.println(name);
}

Note: Enhanced loop can’t modify elements directly.


📌 Array vs ArrayList

Feature Array ArrayList
Fixed size Yes No (resizable)
Type support Primitives + objects Objects only
Syntax arr[i] list.get(i)
Length arr.length list.size()

🧪 Practice Multiple Choice (5 Questions)

1. What does names.size() return?
(A) The largest index
(B) The number of elements
(C) The last element
(D) The capacity of the list
Answer: (B)


2. What is printed?

ArrayList<Integer> nums = new ArrayList<>();
nums.add(1);
nums.add(3);
nums.add(2);
System.out.println(nums.get(1));

(A) 1
(B) 2
(C) 3
(D) Error
Answer: (C)


3. Which of these removes the first item in an ArrayList named words?
(A) words.delete(0);
(B) words.remove(1);
(C) words.remove(0);
(D) words.removeFirst();
Answer: (C)


4. What happens if you use int instead of Integer in an ArrayList?
(A) It works fine
(B) Compilation error
(C) Runtime error
(D) It auto-converts
Answer: (B)


5. Which loop can modify elements in an ArrayList?

for (int i = 0; i < list.size(); i++) {
    list.set(i, list.get(i) + 1);
}

(A) Enhanced for-loop
(B) While-loop only
(C) For-loop with indices
(D) None of these
Answer: (C)