Collections Framework
Master Java's powerful data structure library — the right collection choice can make your program 100x faster.
Learn Collections Framework in our free Java course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free Java course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
📚 Before You Start
- Arrays (Lesson 7) — fixed-size data storage
- OOP (Lesson 9) — classes, objects, and interfaces
- Loops (Lesson 5) — iterating through data
What You'll Learn
- ✅ ArrayList — dynamic resizable arrays for ordered data
- ✅ HashMap — key-value pairs for blazing-fast lookups
- ✅ HashSet — unique elements with O(1) contains checks
- ✅ LinkedList, Stack, and Queue for specialized needs
- ✅ Iterating with for-each, iterators, and streams
- ✅ Choosing the right collection (performance guide)
1️⃣ Why Collections Matter
Real-world analogy: Collections are like different types of storage containers . An ArrayList is a numbered filing cabinet — great for ordered access. A HashMap is a dictionary — look up any word instantly. A HashSet is a bag of unique marbles — quickly check "is this marble in the bag?"
Why not just use arrays? Arrays have a fixed size. Collections resize dynamically, offer rich APIs (search, sort, filter), and provide type safety with generics.
2️⃣ ArrayList — Your Go-To List
Use ArrayList when you need ordered data with fast index access. It's the most commonly used collection.
Performance: O(1) for get/set by index, O(n) for insert/remove in the middle.
3️⃣ HashMap — Key-Value Lookups
Analogy: Like a phone book — you look up a person's name (key) to find their number (value). You don't search page by page; you jump directly to the right entry.
4️⃣ HashSet — Unique Elements
Use HashSet when you need to track unique items. Duplicates are silently ignored.
5️⃣ Which Collection Should I Use?
Need
Use
Why
Ordered list, read by index
ArrayList
O(1) get, auto-resize
Frequent insert/remove at ends
LinkedList
O(1) add/remove at head/tail
Key → value mapping
HashMap
O(1) lookup by key
Sorted key → value
TreeMap
Keys always sorted
Unique elements only
HashSet
O(1) contains check
LIFO (undo, backtracking)
Deque/Stack
push/pop O(1)
FIFO (task queue, BFS)
Queue/LinkedList
offer/poll O(1)
Default choice: Start with ArrayList for lists and HashMap for key-value pairs.
6️⃣ Common Beginner Mistakes
❌ Mistake 1: Modifying a collection while iterating
❌ Mistake 3: Not overriding hashCode() with HashMap keys
If you override equals() , you must also override hashCode() .
📋 Quick Reference
Collection
Key Methods
Complexity
add, get, set, remove, size
O(1) get, O(n) insert
addFirst, addLast, poll
O(1) ends, O(n) middle
put, get, containsKey, remove
O(1) average
put, get, firstKey, lastKey
O(log n) sorted
add, contains, remove
Stack/Deque
push, pop, peek
O(1)
🎉 Lesson Complete!
You now know how to use Java's core collections — ArrayList, HashMap, HashSet, Stack, and Queue — and how to choose the right one based on your data access patterns.
Next up: Generics — write type-safe, reusable code that works with any data type.
Practice quiz
Which collection gives O(1) access by index and resizes automatically?
- LinkedList
- HashSet
- ArrayList
- TreeMap
Answer: ArrayList. ArrayList offers O(1) get by index and grows automatically.
Which collection stores key-value pairs with O(1) average lookup?
- HashMap
- ArrayList
- HashSet
- Stack
Answer: HashMap. HashMap maps keys to values with O(1) average lookup by key.
What happens when you add a duplicate element to a HashSet?
- It throws an exception
- It replaces all copies
- It adds a second copy
- It is silently ignored
Answer: It is silently ignored. A HashSet keeps only unique elements; duplicates are silently ignored.
Modifying a list with remove() inside a for-each loop typically throws...
- NullPointerException
- ConcurrentModificationException
- IndexOutOfBoundsException
- Nothing
Answer: ConcurrentModificationException. Structurally modifying a collection during for-each iteration throws ConcurrentModificationException; use removeIf instead.
Which collection should you use to keep keys always sorted?
- TreeMap
- HashMap
- LinkedList
- HashSet
Answer: TreeMap. TreeMap keeps its keys sorted (O(log n) operations).
If you override equals() on a class used as a HashMap key, you must also override...
- toString()
- compareTo()
- hashCode()
- clone()
Answer: hashCode(). Override hashCode() whenever you override equals(), or HashMap lookups break.
What does 'List list = new ArrayList();' (a raw type) sacrifice?
- Nothing
- Type safety
- All methods
- The import
Answer: Type safety. Raw types lose generic type safety; always parameterize, e.g. List<String>.
Which structure follows LIFO (Last-In-First-Out), good for undo?
- Queue
- TreeMap
- HashSet
- Stack/Deque
Answer: Stack/Deque. A Stack/Deque is LIFO — push/pop from the same end, ideal for undo.
After Deque history = new ArrayDeque<>(); push('a'); push('b'); push('c'); what does pop() return?
- a
- c
- b
- null
Answer: c. push adds to the top and pop removes from the top, so the last pushed ('c') comes out first.
A Queue (FIFO) removes elements in what order via poll()?
- Last added first
- Random order
- First added first
- Sorted order
Answer: First added first. A Queue is FIFO: poll() returns the earliest-added element first.
Continue this course
- Previous: Previous Lesson
- Next: Next Lesson