ArrayList, Strings and StringBuilder
ArrayList is the everyday list in Java - it grows as you add items. Strings are immutable, so building text in loops should use StringBuilder. Both appear in most interview questions.
ArrayList: an array that grows
Example
addat the end: O(1) on average;get(i): O(1)add(0, x),remove(0),contains: O(n)- Lists hold objects, so
intbecomesInteger(autoboxing)
Strings are immutable
Example
StringBuilder for building text
Each + on strings in a loop makes a new string - O(n²) overall. StringBuilder appends in place:
Example
Counting characters
Example
Key points
- ArrayList grows automatically; add at end is fast.
- Compare strings with equals.
- Use StringBuilder to build strings in loops.
📝 Test yourself
1. Why use StringBuilder in a loop?
2. How should you compare two Strings' text?
3. Fill in the ArrayList method that returns the number of items:
cart.()
