Intermediate · The collections framework · topic 31 of 60 · 30 min
Collections overview and List
Explanation
Why a framework?
Arrays have a fixed size and few features. Almost every program needs growing lists, unique sets and lookups by key. Java's collections framework (in java.util) provides tested, fast implementations behind a few common interfaces, so code written against List works with any list.
Collection
├── List (ordered, duplicates allowed) → ArrayList, LinkedList
├── Set (no duplicates) → HashSet, LinkedHashSet, TreeSet
└── Queue (processing order) → ArrayDeque, PriorityQueue, LinkedList
Map (separate: key → value) → HashMap, LinkedHashMap, TreeMapArrayList
List<String> cart = new ArrayList<>();
cart.add("Rice"); // append
cart.add("Dal");
cart.add(0, "Oil"); // insert at index 0: [Oil, Rice, Dal]
System.out.println(cart.get(1)); // Rice
cart.set(2, "Moong dal"); // replace
cart.remove("Rice"); // by value → [Oil, Moong dal]
System.out.println(cart.size() + " " + cart.contains("Oil")); // 2 true
for (String item : cart) System.out.println(item);ArrayList stores elements in an internal array that grows (roughly by half) when full. get(i) and set(i) are instant (O(1)); adding at the end is fast on average; inserting or removing in the middle shifts later elements (O(n)).
ArrayList versus LinkedList
| Operation | ArrayList | LinkedList |
|---|---|---|
| get(i) | O(1) fast | O(n) walks the chain |
| add at end | O(1) amortised | O(1) |
| add/remove at the start | O(n) | O(1) |
| Memory per element | Small | Larger (node objects with links) |
| Use when | Almost always | Rarely; ArrayDeque is usually better for queues |
Immutable lists
List<String> zones = List.of("North", "South", "East", "West"); // unmodifiable (Java 9+)
// zones.add("Central"); // UnsupportedOperationException at run time
List<String> copy = new ArrayList<>(zones); // a modifiable copyRemoving while iterating
List<Integer> amounts = new ArrayList<>(List.of(100, -5, 250, 0, 80));
// for (Integer a : amounts) if (a <= 0) amounts.remove(a); // ConcurrentModificationException
amounts.removeIf(a -> a <= 0); // Java 8+: [100, 250, 80]
Iterator<Integer> it = amounts.iterator(); // the classic way
while (it.hasNext()) if (it.next() > 200) it.remove(); // [100, 80]Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Collections overview and List · 1/6
In this lesson you will meet the collections framework and use List.
Prefer a video by a teacher? Find free videos on “java collections framework arraylist vs linkedlist tutorial” on YouTube ↗
In real life: A delivery route list
A delivery app keeps the day's drop-off addresses in an ArrayList. The rider sees them in order; cancelled orders are removed with removeIf, and an urgent order is inserted at the front.
List<String> stops = new ArrayList<>(List.of("A-12 Kothrud", "C-4 Aundh", "B-7 Baner"));
stops.removeIf(s -> s.startsWith("C-")); // order C-4 was cancelled
stops.add(0, "URGENT: D-1 Wakad");
System.out.println(stops); // [URGENT: D-1 Wakad, A-12 Kothrud, B-7 Baner]Practice (0/3 done)
What does this print? List<Integer> l = new ArrayList<>(List.of(5, 7, 1)); l.remove(1); System.out.println(l);
What happens? List<String> l = List.of("a", "b"); l.add("c");
Write a program that stores 8 order amounts in an ArrayList<Integer>, removes the refunded ones (amounts below 0) with removeIf, inserts a new order at the front, and prints the size, the total and the list. Then show the remove(int) versus remove(Object) trap with a comment.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Sets: HashSet, LinkedHashSet and TreeSetThe collections framework · same module
- Maps: HashMap, LinkedHashMap and TreeMapThe collections framework · same module
- Sorting with Comparable and ComparatorThe collections framework · same module
- Sets: each item only oncePython Programming · Lists, tuples, dictionaries and sets
- Iterators: the glue between containers and algorithmsC++ Programming (modern C++ and DSA) · The Standard Template Library (STL)
- Queues and dequesData Structures and Algorithms (DSA) for interviews · Stacks, queues and linked lists
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which interface does NOT extend Collection?
Answer: Map
Map is a separate hierarchy.
Which is fastest for get(500000)?
Answer: ArrayList
ArrayList has O(1) random access.
Removing elements inside a for-each loop over an ArrayList usually throws…
Answer: ConcurrentModificationException
The iterator detects the structural change.
Does a List allow duplicates?
Answer: Yes
Lists keep every element in order, duplicates included.
How do you make an empty set?Related
Answer: set()
{} makes an empty dict. The only way to make an empty set is set().
What does it->first give for a std::map iterator?Related
Answer: The key
Map elements are pairs: first is the key, second is the value.
Which deque operation is NOT O(1)?Related
Answer: q[len(q) // 2]
A deque is a linked structure of blocks: both ends are O(1), the middle is O(n).
From Queues and deques
Why must a HashMap key override both equals and hashCode?Related
Answer: So equal keys land in the same bucket and are found
The contract keeps lookups correct.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 4 more topics in “The collections framework” before its exam: Sets: HashSet, LinkedHashSet and TreeSet, Maps: HashMap, LinkedHashMap and TreeMap, Sorting with Comparable and Comparator, Queues, stacks and priority queues.
- Module 7 exam: The collections framework · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Lambdas, streams and files. 60 topics left in the course before the final exam.