ArrayList
While arrays are perfect for storing fixed-size data, most real-world applications need collections that can grow and shrink dynamically.
This is where ArrayList shines.
An ArrayList
works much like an array but can automatically resize as you add or remove elements.
Internally, it uses a standard array but manages resizing for you.
Key features of ArrayList:
Add elements anytime with .add()
Remove elements with .remove()
Insert elements at any position
Size changes dynamically
Stores only objects, so you canโt put primitives directly (Java auto-boxes them, e.g. int
becomes Integer
)
ArrayList is great for:
To-do lists,
Shopping carts,
Dynamic search results,
Building and filtering collections on the fly.
Mini Lab
An ArrayList
works naturally with both for loops and enhanced for-each loops.
Unlike arrays, you use .size()
instead of .length
.
You also use .get(index)
to access items by index.
Looping over an ArrayList is common for:
Displaying items,
Searching,
Filtering or transforming data,
Calculating totals.
Mini Lab
When should you choose a plain array vs. an ArrayList?
Use an array if:
You know the exact size up front.
You need maximum speed and low memory overhead.
You work with performance-critical code.
Use ArrayList if:
You donโt know how many items youโll have.
You need to add, insert, or remove items freely.
You want built-in methods for collection operations.
In practice, ArrayList is the go-to choice for general-purpose lists in modern Java.
But arrays still shine for small, simple, or low-level operations.
Mini Lab