← Back to Week 3 Hub

ArrayList Operations

An ArrayList<Product> — each item is a Product object (id, name, price). Try every method and watch the list update.

The inventory is made of objects. Each row is a Product with id, name, and price. The ArrayList stores references to those objects in order, and every method (add, get, set, remove, size, clear) works by index.
ArrayList<Product> inventory
size(): 0
add — put at end
add(index, item) — insert at position
index
get(index)
index
set(index, item) — replace
index
remove(index) — shifts others down
index
bulk
Call log

ArrayList methods — reference

.add(item)
Appends the item to the end of the list.
.add(index, item)
Inserts the item at that index; items at and after shift up by one.
.get(index)
Returns the item at that index. Throws if out of range.
.set(index, item)
Replaces the item at that index with a new one.
.remove(index)
Removes the item at that index; items after shift down by one.
.size()
Returns how many items are in the list right now.
.clear()
Removes all items. size() becomes 0.
Collections.sort(list)
Sorts the list in-place using the natural ordering or a Comparator.

Tip: watch the indexes after a remove. Everything after the removed item shifts down — the indexes update. That's why you can't remove items while iterating with a regular for loop.

← Array vs ArrayList HashMap Hashing & Buckets →