ArrayList: The Dynamic Alternative
In Java, a standard Array is like a fixed-size parking lot—once you build it for 10 cars, you can never park an 11th one. An ArrayList, however, is like an accordion; it grows and shrinks automatically as you add or remove items.
1. Key Differences
| Feature | Standard Array ([]) |
ArrayList |
|---|---|---|
| Size | Fixed (cannot change) | Dynamic (resizable) |
| Type | Primitives or Objects | Objects only (use Wrappers like Integer) |
| Syntax | array[0] = 10; |
list.add(10); |
| Performance | Faster for basic tasks | Slightly slower, but much more flexible |
2. Importing and Creating
To use it, you must import it from the java.util package.
import java.util.ArrayList;
// Syntax: ArrayList<DataType> name = new ArrayList<>();
ArrayList<String> tools = new ArrayList<>();
3. Common Operations
| Action | Method | Example |
|---|---|---|
| Add | .add(value) |
tools.add("Git"); |
| Access | .get(index) |
String s = tools.get(0); |
| Modify | .set(index, value) |
tools.set(0, "Zsh"); |
| Remove | .remove(index) |
tools.remove(0); |
| Size | .size() |
int len = tools.size(); |
| Clear | .clear() |
tools.clear(); // Empty the list |
4. ArrayList with Primitive Types
Since ArrayLists only store Objects, you cannot use int, double, or boolean directly. Instead, Java uses Wrapper Classes:
int→Integerdouble→Doubleboolean→Boolean
ArrayList<Integer> scores = new ArrayList<>(); // Correct
// ArrayList<int> scores = new ArrayList<>(); // Error!
💻 Full Practical Example: The Task Manager
Copy this code to see how easy it is to manage a changing list of data:
import java.util.ArrayList;
import java.util.Collections; // Bonus: for sorting!
public class TaskList {
public static void main(String[] args) {
ArrayList<String> tasks = new ArrayList<>();
// Adding items
tasks.add("Fix Hyprland config");
tasks.add("Complete Java Lab");
tasks.add("Buy thermal paste");
// Removing an item
tasks.remove(0);
// Checking the list
System.out.println("Remaining Tasks: " + tasks.size());
// Sorting the list alphabetically
Collections.sort(tasks);
// Standard Loop
for (int i = 0; i < tasks.size(); i++) {
System.out.println((i + 1) + ". " + tasks.get(i));
}
}
}
💡 Challenge: The Dynamic Inventory
- Create an
ArrayListofStringcalledinventory. - Add four items to it (e.g., "CPU", "GPU", "RAM", "SSD").
- Use an
ifstatement with.contains("GPU")to check if a graphics card is in stock. - Replace "SSD" with "M.2 NVMe" using the
.set()method. - Print the final list using a ForEach loop.