Part 04 / Topic 5 of 10
ArrayList<T>: a resizable, ready-made list
Treat ArrayList<T> as a tool you use, not a mechanism you need to understand internally yet (that depth is Stage 2 Part 9). The pattern to copy: write the diamond <> with your type once, on the declaration, and Java fills it in for every method call after that.
import java.util.ArrayList;
class ArrayListBasics {
public static void main(String[] args) {
// The diamond <> is a recipe: write the type once, on the left, and copy it.
ArrayList<String> cart = new ArrayList<>();
cart.add("Rice");
cart.add("Dal");
cart.add("Milk");
System.out.println(cart);
System.out.println("Items: " + cart.size());
cart.add(1, "Sugar"); // insert at index 1; everything after it shifts right
System.out.println(cart);
cart.set(0, "Basmati Rice"); // replace whatever is at index 0
System.out.println(cart.get(0));
cart.remove("Milk"); // remove by value (there is also remove(int index))
System.out.println(cart);
System.out.println(cart.contains("Dal"));
System.out.println(cart.contains("Milk"));
for (String item : cart) {
System.out.println("- " + item);
}
cart.clear();
System.out.println(cart.isEmpty());
}
}
Output (examples/04_array_list_basics.java):
[Rice, Dal, Milk]
Items: 3
[Rice, Sugar, Dal, Milk]
Basmati Rice
[Basmati Rice, Sugar, Dal]
true
false
- Basmati Rice
- Sugar
- Dal
true
A few things worth noticing:
System.out.println(cart)prints anArrayListdirectly in a readable[a, b, c]form — unlike a plain array,ArrayListknows how to describe itself.remove("Milk")removes by value here because"Milk"is aString.remove(1)would remove by index instead — be careful which overload you're calling, especially withArrayList<Integer>(section 6 explains why).- A for-each loop works on
ArrayList<T>exactly like it did on an array.
🔍 Going deeper:
ArrayListis one implementation of theListinterface. Stage 2 Part 9 coversList/Set/Map/Dequeas interfaces with several implementations each, and when to pick which one. For now,ArrayListis your one default "resizable list."
Full program: examples/04_array_list_basics.java.
Done here? The practice set for Part 4 — including the solutions — is on the part page.