Concept Explanation
Imagine a built-in array like a Cinema Row with 10 seats. If an 11th person arrives, you're stuck. To fit them, you'd have to build an entirely new row and move everyone over.
An ArrayList is like an Accordion Row. When it gets full, it automatically grows. It manages the "Building a new row and moving everyone" logic for you behind the scenes.
Syntax or Core Structure
ArrayList is part of the java.util package. It uses Generics (<Type>) to define what it holds.
import java.util.ArrayList;
ArrayList<String> shoppingList = new ArrayList<>();
shoppingList.add("Milk"); // [Milk]
shoppingList.add("Eggs"); // [Milk, Eggs]
shoppingList.get(0); // "Milk"
shoppingList.size(); // 2
shoppingList.remove(1); // Removes "Eggs"
Common Mistakes
- Primitives in Generic Args: You cannot do
ArrayList<int>. You must use the Wrapper Class:ArrayList<Integer>. - Size vs Length: Arrays use
.length, but ArrayLists use.size(). - Removal during loop: If you remove an item from an ArrayList while looping through it with a regular for-loop, you might skip items. Use an Iterator for safe removal.
Practice Exercises
- The Guest List: Create an ArrayList of names. Add 5 names, remove the 3rd one, and print the remaining list.
- The Number Sorter: Research
Collections.sort(). Create an ArrayList of integers and sort them from smallest to largest. - The Capacity Test: Research how an ArrayList grows. What is its "Default Capacity" and "Load Factor"?