Collection Framework
Lists, Sets, Maps, internals of HashMap, and collection hierarchies
- Master List, Set, and Map hierarchies
- Understand how HashMap works internally (hashing, collision, treeifying)
- Choose the right collection for the right problem
Table of Contents
- What is a Collection?
- What is a Framework?
- What is the Java Collection Framework (JCF)?
- Why Was JCF Needed? — The Problem It Solved
- JCF Hierarchy — Complete Overview
- The
IterableInterface - Three Ways to Iterate a Collection
- The
CollectionInterface - Common Methods of
Collection - Collection vs Collections — Key Difference
- The
MapInterface — Why It's Separate - Interview Notes
- Summary & Quick Revision
- Practice Questions
1. What is a Collection?
Overview
Before diving into the framework, you need to understand what a collection is at its core.
Definition
A collection is a group of objects (also called a group of elements) stored together under a single unit.
Real-world Analogy
Think of a bag of fruits. The bag is the collection; the individual fruits are the elements. You can add a fruit, remove a fruit, search for a fruit, and count how many fruits are in the bag.
Examples of Collections
Even before the Java Collection Framework existed, Java had types that acted as collections:
| Type | Description |
|---|---|
Array | A fixed-size sequential collection of elements of the same type |
Vector | A resizable array (thread-safe, available before JCF) |
Hashtable | A key-value store (available before JCF) |
Example Array as a Collection
1// Creating an integer array (a collection of integers)2int[] a = {1, 2, 3, 4};3
4// Writing (inserting) to an array5a[0] = 1;6
7// Reading from an array8int value = a[0]; // value = 1Example Vector as a Collection
1import java.util.Vector;2
3// Creating a Vector of integers4Vector<Integer> v = new Vector<>();5
6// Writing (inserting) into a Vector7v.add(10);8
9// Reading from a Vector10int value = v.get(0); // value = 10Package
All Java collection classes and interfaces are located in the java.util package.
1import java.util.*; // imports all collection classesVersion History
| Feature | Added In |
|---|---|
Array, Vector, Hashtable | Java 1.0 / 1.1 |
| Java Collection Framework (JCF) | Java 1.2 |
Iterable interface | Java 1.5 |
forEach() method, Streams | Java 1.8 |
2. What is a Framework?
Definition
A framework is a pre-built architecture that provides:
- Ready-made classes and interfaces
- Common methods and functionality
- A standardized structure you can build upon
What JCF's Framework Provides
- Classes like
ArrayList,LinkedList,Stack,HashSet,TreeSet, etc. - Interfaces like
Iterable,Collection,List,Set,Queue,Map - Pre-built methods:
add(),remove(),contains(),size(),clear(),sort(), etc.
3. What is the Java Collection Framework (JCF)?
Definition
The Java Collection Framework (JCF) is a unified architecture of classes and interfaces that represent and manipulate groups of objects (collections). It was introduced in Java 1.2.
What It Contains
- Interfaces: Define the contract (what operations are available)
- Concrete Classes: Implement those interfaces with specific behavior
- Utility Classes: Provide helper methods (e.g.,
Collections) - Algorithms: Sorting, searching, shuffling, etc.
Core Capabilities
With JCF, you can perform these operations on any collection:
- Add elements
- Remove elements
- Update elements
- Search for elements
- Iterate over elements
- Sort elements
4. Why Was JCF Needed? The Problem It Solved
The Problem: No Common Interface
Before JCF (before Java 1.2), Java had Array, Vector, and Hashtable — but each used completely different methods for reading and writing. There was no common interface.
Comparison of Pre-JCF Collections
| Operation | Array | Vector | Hashtable |
|---|---|---|---|
| Insert | a[0] = value | v.addElement(value) | ht.put(key, value) |
| Read | a[0] | v.get(0) | ht.get(key) |
| Size | a.length | v.size() | ht.size() |
Code Example Demonstrating the Problem
1// Array — index-based read/write2int[] array = new int[4];3array[0] = 1; // Write4int val = array[0]; // Read5
6// Vector — method-based read/write (different syntax!)7Vector<Integer> vector = new Vector<>();8vector.add(10); // Write9int val2 = vector.get(0); // Read10
11// Hashtable — key-value based (completely different!)12Hashtable<String, Integer> ht = new Hashtable<>();13ht.put("key", 10); // Write14int val3 = ht.get("key"); // Readarray[0]=, then vector.add(), then ht.put(). Three different ways to do the same thing. Developers had to memorize different syntax for every collection type.The Solution: A Common Interface
JCF introduced a common parent interface called Collection. Now, all collection classes implement Collection, which means they all share the same method names:
| Operation | Any JCF Collection |
|---|---|
| Insert | .add(element) |
| Remove | .remove(element) |
| Search | .contains(element) |
| Size | .size() |
| Iterate | .iterator() / enhanced for loop |
Code Example Demonstrating the Solution
1import java.util.*;2
3// ArrayList — uses .add() to insert4List<Integer> list = new ArrayList<>();5list.add(1);6
7// Stack — also uses .add() to insert8Stack<Integer> stack = new Stack<>();9stack.add(2);10
11// LinkedList — also uses .add() to insert12LinkedList<Integer> linkedList = new LinkedList<>();13linkedList.add(3);14
15// PriorityQueue — also uses .add() to insert16PriorityQueue<Integer> pq = new PriorityQueue<>();17pq.add(4);Now you only need to remember one method name regardless of which collection you use. This is the power of a common interface.
5. JCF Hierarchy Complete Overview
The Two Trees
JCF is organized into two separate hierarchies:
- The
Iterable/Collectiontree — for single-element collections (lists, sets, queues) - The
Maptree — for key-value pair collections (maps)
Map is NOT a child of Collection or Iterable. It is a completely separate hierarchy. This is a common interview question.Visual Hierarchy Diagram
Legend:
- 🔵 Light blue = Interface
- 🩷 Pink = Concrete class (under
Collectionhierarchy) - 🟣 Purple = Concrete class (under
Maphierarchy)
Concrete Classes Reference Table
| Concrete Class | Parent Interface | Key Characteristic |
|---|---|---|
ArrayList | List | Resizable array, index-based access |
LinkedList | List, Deque | Doubly linked list, fast insertions |
Vector | List | Thread-safe resizable array (legacy) |
Stack | Vector | LIFO (Last In, First Out) |
PriorityQueue | Queue | Elements ordered by priority |
ArrayDeque | Deque | Double-ended queue |
HashSet | Set | No duplicates, unordered |
LinkedHashSet | Set | No duplicates, insertion-ordered |
TreeSet | SortedSet | No duplicates, sorted order |
HashMap | Map | Key-value pairs, unordered |
LinkedHashMap | Map | Key-value pairs, insertion-ordered |
TreeMap | Map | Key-value pairs, sorted by key |
Hashtable | Map | Thread-safe key-value pairs (legacy) |
6. The `Iterable` Interface
Overview
Iterable is the root interface of the entire Collection hierarchy. It is defined in java.lang (not java.util) and was added in Java 1.5.
Purpose
Iterable exists to give all collections the ability to be traversed (iterated). By implementing Iterable, a class can be used in an enhanced for loop (for-each loop).
iterator() method was already available directly on the Collection interface since Java 1.2. In Java 1.5, the Iterable interface was introduced as a separate parent of Collection to expose iteration at a higher level — enabling the enhanced for-each loop syntax and allowing non-collection objects (like custom classes) to also be iterable.Key Methods of `Iterable`
| Method | Added In | Description |
|---|---|---|
iterator() | Java 1.5 | Returns an Iterator object for traversal |
forEach(Consumer action) | Java 1.8 | Iterates using a lambda expression |
spliterator() | Java 1.8 | Returns a Spliterator (for parallel processing) |
Class Diagram
7. Three Ways to Iterate a Collection
All three methods are available on any class that implements Iterable (which includes all JCF collections like ArrayList, LinkedList, Stack, HashSet, etc.)
Method 1: Using `iterator()` The `Iterator` Object
What is an `Iterator`?
iterator() is a method defined on the Iterable interface. When called, it returns an Iterator object — a cursor that steps through the collection one element at a time.
Methods of the `Iterator` Object
| Method | Return Type | Description |
|---|---|---|
hasNext() | boolean | Returns true if there are more elements to iterate |
next() | E (element type) | Returns the next element and advances the cursor |
remove() | void | Removes the last element returned by next() from the collection |
remove() on an Iterator is the safe way to remove elements while iterating. Removing from a collection directly inside a loop causes a ConcurrentModificationException.Code Example
1import java.util.ArrayList;2import java.util.Iterator;3import java.util.List;4
5public class IteratorExample {6 public static void main(String[] args) {7
8 // Step 1: Create and populate a collection9 List<Integer> values = new ArrayList<>();10 values.add(1);11 values.add(2);12 values.add(3);13 values.add(4);14 // values = [1, 2, 3, 4]15
16 // Step 2: Get an Iterator object17 Iterator<Integer> valueIterator = values.iterator();18
19 // Step 3: Iterate using hasNext() and next()20 while (valueIterator.hasNext()) {21 Integer value = valueIterator.next();22 System.out.println(value);23
24 // Step 4: Remove element with value 3 while iterating25 if (value == 3) {26 valueIterator.remove(); // Safe removal during iteration27 }28 }29
30 // Step 5: Print remaining elements31 System.out.println("After removal: " + values);32 // values = [1, 2, 4] (3 was removed)33 }34}Output
112233445After removal: [1, 2, 4]Step-by-Step Execution
Line-by-Line Explanation
| Line | Explanation |
|---|---|
values.iterator() | Returns an Iterator object. The cursor is positioned before the first element. |
valueIterator.hasNext() | Checks if the cursor has a next element. Returns true initially because element 1 exists. |
valueIterator.next() | Moves the cursor to element 1 and returns it. |
if (value == 3) | Checks whether the current element is 3. |
valueIterator.remove() | Removes 3 from the underlying values list. This is safe because the iterator tracks the state. |
Method 2: Enhanced `for` Loop (for-each)
Overview
Any class that implements Iterable can be used in an enhanced for loop. This is the simplest and most common way to iterate when you don't need to remove elements.
Syntax
1for (ElementType variable : collection) {2 // use variable3}Code Example
1import java.util.ArrayList;2import java.util.List;3
4public class ForEachLoopExample {5 public static void main(String[] args) {6 List<Integer> values = new ArrayList<>();7 values.add(1);8 values.add(2);9 values.add(4); // Remember: 3 was removed in the previous example10
11 // Enhanced for loop — iterates over each element12 for (Integer value : values) {13 System.out.println(value);14 }15 }16}Output
112234How It Works Internally
The enhanced for loop is syntactic sugar — the Java compiler converts it into an Iterator-based loop behind the scenes:
1// What you write:2for (Integer value : values) {3 System.out.println(value);4}5
6// What the compiler generates:7Iterator<Integer> it = values.iterator();8while (it.hasNext()) {9 Integer value = it.next();10 System.out.println(value);11}values.remove() inside an enhanced for loop. Since the compiler generates an iterator internally, modifying the collection directly while iterating will throw ConcurrentModificationException. Use Iterator.remove() (Method 1) or use removeIf() instead.Method 3: `forEach()` Method with Lambda Expression
Overview
Added in Java 1.8, the forEach() method is defined on the Iterable interface. It accepts a Consumer functional interface and uses a lambda expression to process each element.
What is `Consumer`?
Consumer is a built-in functional interface in java.util.function. It has one abstract method:
1void accept(T t);It takes one input and returns nothing (void). It is used to represent an action to be performed on each element.
Syntax
1collection.forEach(element -> {2 // action on element3});4
5// Or with a single statement:6collection.forEach(element -> System.out.println(element));7
8// Or with a method reference:9collection.forEach(System.out::println);Code Example
1import java.util.ArrayList;2import java.util.List;3
4public class ForEachMethodExample {5 public static void main(String[] args) {6 List<Integer> values = new ArrayList<>();7 values.add(1);8 values.add(2);9 values.add(4);10
11 // forEach() with a lambda expression12 values.forEach(value -> System.out.println(value));13 }14}Output
112234Internal Mechanism
1// values.forEach(value -> System.out.println(value));2// is equivalent to:3
4for (Integer value : values) {5 // The Consumer's accept() method is called with each element6 System.out.println(value); // the lambda body7}The forEach() method internally loops over every element and invokes the provided Consumer's accept() method, passing each element as the argument T.
Comparison of All Three Iteration Methods
| Feature | iterator() | Enhanced for | forEach() |
|---|---|---|---|
| Java Version | 1.2 (iterator object) / 1.5 (interface) | 1.5 | 1.8 |
| Safe removal during iteration | ✅ Yes (iterator.remove()) | ❌ No | ❌ No (use removeIf()) |
| Syntax simplicity | Medium | High | High |
| Uses lambda | ❌ No | ❌ No | ✅ Yes |
| Use when... | Need to remove during iteration | Simple read-only traversal | Functional-style processing |
8. The `Collection` Interface
Overview
Collection is the second level in the JCF hierarchy, directly below Iterable. It is an interface that represents a group of objects (elements) and defines the core operations available on all single-element collections.
Definition
Collectionis the root interface of the JCF collection hierarchy (underIterable). It defines the basic contract that all collections must fulfill.
What Extends/Implements Collection
List(interface) — extendsCollection; ordered, allows duplicatesSet(interface) — extendsCollection; unordered, no duplicatesQueue(interface) — extendsCollection; ordered for processing (FIFO by default)
9. Common Methods of `Collection`
All the methods listed below are defined in the Collection interface and are therefore available on every concrete collection class (ArrayList, Stack, LinkedList, PriorityQueue, HashSet, TreeSet, etc.)
Method Reference Table
| Method | Return Type | Added In | Description |
|---|---|---|---|
size() | int | 1.2 | Returns total number of elements |
isEmpty() | boolean | 1.2 | Returns true if collection has no elements |
contains(Object o) | boolean | 1.2 | Returns true if element is present |
add(E e) | boolean | 1.2 | Inserts an element |
remove(Object o) | boolean | 1.2 | Removes first occurrence of element |
addAll(Collection c) | boolean | 1.2 | Inserts all elements from another collection |
removeAll(Collection c) | boolean | 1.2 | Removes all elements that exist in given collection |
containsAll(Collection c) | boolean | 1.2 | Returns true if all elements of given collection are present |
clear() | void | 1.2 | Removes ALL elements from the collection |
equals(Object o) | boolean | 1.2 | Checks if two collections are equal |
toArray() | Object[] | 1.2 | Converts collection to an array |
iterator() | Iterator | 1.2 | Returns an iterator |
stream() | Stream | 1.8 | Returns a sequential stream |
parallelStream() | Stream | 1.8 | Returns a parallel stream |
Complete Code Example All Methods Demonstrated
1import java.util.ArrayList;2import java.util.List;3import java.util.Stack;4
5public class CollectionMethodsExample {6 public static void main(String[] args) {7
8 // ── Create collection and add elements ──9 List<Integer> values = new ArrayList<>();10 values.add(2);11 values.add(3);12 values.add(4);13 // values = [2, 3, 4]14
15 // ── size() ──16 System.out.println(values.size()); // 317
18 // ── isEmpty() ──19 System.out.println(values.isEmpty()); // false20
21 // ── contains() ──22 System.out.println(values.contains(5)); // false23
24 // ── add() ──25 values.add(5);26 System.out.println(values.contains(5)); // true27 // values = [2, 3, 4, 5]28
29 // ── remove() by INDEX (primitive int) ──30 values.remove(3); // removes element at index 3 (value = 5)31 System.out.println(values.contains(5)); // false32 // values = [2, 3, 4]33
34 // ── remove() by OBJECT (Integer wrapper) ──35 values.remove(Integer.valueOf(3)); // removes the element with value 336 System.out.println(values.contains(3)); // false37 // values = [2, 4]38
39 // ── addAll() — merge another collection into this one ──40 Stack<Integer> stackValues = new Stack<>();41 stackValues.add(6);42 stackValues.add(7);43 stackValues.add(8);44
45 values.addAll(stackValues);46 // values = [2, 4, 6, 7, 8]47
48 // ── containsAll() — check if all elements of stackValues are in values ──49 System.out.println(values.containsAll(stackValues)); // true50
51 // ── remove element 7 manually ──52 values.remove(Integer.valueOf(7));53 // values = [2, 4, 6, 8]54
55 // ── containsAll() again — now 7 is missing ──56 System.out.println(values.containsAll(stackValues)); // false (7 is missing)57
58 // ── removeAll() — remove all elements that are in stackValues (6, 7, 8) ──59 values.removeAll(stackValues);60 // 6 and 8 get removed (7 was already removed)61 // values = [2, 4]62
63 System.out.println(values.contains(8)); // false64
65 // ── clear() ──66 values.clear();67 System.out.println(values.isEmpty()); // true68 }69}Output
132false3false4true5false6false7true8false9false10trueImportant: `remove()` by Index vs. by Object
This is a very common source of bugs in Java.
1List<Integer> list = new ArrayList<>();2list.add(10);3list.add(20);4list.add(30);5// list = [10, 20, 30] (indices 0, 1, 2)6
7// Removes by INDEX — removes element at index 1 (which is value 20)8list.remove(1);9// list = [10, 30]10
11// Removes by OBJECT VALUE — removes element with value 1012list.remove(Integer.valueOf(10));13// list = [30]list.remove(int) with a primitive int, Java treats it as an index.
When calling list.remove(Integer) with an Integer object (wrapper), Java treats it as the value to search for and remove.
Always use Integer.valueOf(n) or (Integer) n to remove by value from a List.The Power of Common Methods
Because all concrete classes inherit these methods from Collection, you only need to learn the method names once:
1// The same .add() works on ALL of these:2ArrayList<Integer> arrayList = new ArrayList<>();3LinkedList<Integer> linkedList = new LinkedList<>();4Stack<Integer> stack = new Stack<>();5PriorityQueue<Integer> pq = new PriorityQueue<>();6HashSet<Integer> hashSet = new HashSet<>();7
8arrayList.add(1); // ✅ works9linkedList.add(1); // ✅ works10stack.add(1); // ✅ works11pq.add(1); // ✅ works12hashSet.add(1); // ✅ works10. `Collection` vs `Collections` Key Difference
This is one of the most commonly confused pairs in Java and a frequent interview question.
Side-by-Side Comparison
| Feature | Collection | Collections |
|---|---|---|
| Type | Interface | Utility Class |
| Package | java.util | java.util |
| Purpose | Blueprint for all collection types | Provides helper/utility methods to work on collections |
| Methods | Instance methods (overridden by concrete classes) | All static methods |
| Part of JCF? | Yes — it's the core interface | Yes — it's a utility layer on top |
| Example use | List | Collections.sort(list) |
What is a Utility Class?
A utility class is a class where all methods are static. You call the methods using the class name directly — no object creation needed.
Common `Collections` (Utility Class) Methods
| Method | Description |
|---|---|
Collections.sort(list) | Sorts list in natural (ascending) order |
Collections.sort(list, comparator) | Sorts using custom comparator |
Collections.reverse(list) | Reverses the order of elements |
Collections.shuffle(list) | Randomly shuffles elements |
Collections.min(collection) | Returns the minimum element |
Collections.max(collection) | Returns the maximum element |
Collections.swap(list, i, j) | Swaps elements at indices i and j |
Collections.copy(dest, src) | Copies all elements from src to dest |
Collections.binarySearch(list, key) | Binary search (list must be sorted) |
Collections.rotate(list, distance) | Rotates elements by given distance |
Collections.frequency(collection, obj) | Returns count of given element |
Collections.unmodifiableList(list) | Returns a read-only view of list |
Code Example
1import java.util.ArrayList;2import java.util.Collections;3import java.util.List;4
5public class CollectionsUtilityExample {6 public static void main(String[] args) {7
8 List<Integer> list = new ArrayList<>();9 list.add(3);10 list.add(1);11 list.add(2);12 list.add(4);13 // list = [3, 1, 2, 4]14
15 // max — static method, called on class name16 System.out.println(Collections.max(list)); // 417
18 // min19 System.out.println(Collections.min(list)); // 120
21 // sort22 Collections.sort(list);23
24 // iterate using forEach25 list.forEach(value -> System.out.print(value + " "));26 // Output: 1 2 3 427
28 // reverse29 Collections.reverse(list);30 list.forEach(value -> System.out.print(value + " "));31 // Output: 4 3 2 132 }33}Output
142131 2 3 444 3 2 1Collection (no S) as the house blueprint — it defines the structure.
Think of Collections (with S) as the toolbox — it provides tools to work on houses already built.11. The `Map` Interface Why It's Separate
Why Is `Map` Not Under `Collection` or `Iterable`?
This is a common interview question. The reason is structural:
Collectionstores single elements:[1, 2, 3, 4]Mapstores key-value pairs:{"name": "Alice", "age": 30}
Because a Map works on pairs of objects (key + value) rather than individual objects, it would not make semantic sense to force it under the Collection interface. The iteration model is different too — you iterate over entries (pairs), keys, or values, not a single sequence of elements.
Map Hierarchy
| Implementation | Description |
|---|---|
HashMap | Unordered key-value store; one null key allowed |
LinkedHashMap | Maintains insertion order |
TreeMap | Sorted by key (natural or comparator order) |
Hashtable | Legacy thread-safe map; no null keys or values |
forEach, and other iteration utilities are available on Map via .entrySet(), .keySet(), and .values() — which all return Collection types. So you still get the power of the Collection framework when working with maps.12. Interview Notes
Commonly Asked Questions
Q1: What is the Java Collection Framework?
A: JCF is a unified architecture introduced in Java 1.2 that provides interfaces, concrete classes, and utility methods to store, retrieve, and manipulate groups of objects. It solved the problem of inconsistent APIs across pre-JCF data structures like Array, Vector, and Hashtable.
Q2: Why was JCF introduced?
A: Before JCF (Java 1.2), there was no common interface for different collection types. Each had its own read/write API:
- Arrays used index-based access (
a[0]) - Vector used
.addElement()/.get() - Hashtable used
.put()/.get()
JCF introduced a common parent interface (Collection) so all collections share the same method signatures, making code easier to write and maintain.
Q3: What is the difference between `Collection` and `Collections`?
A:
Collection— an interface that is the root of the JCF hierarchy (belowIterable). Defines operations likeadd(),remove(),size(), etc.Collections— a utility class with all-static methods (sort(),min(),max(),reverse(), etc.) that operate on collection objects.
Q4: Why is `Iterable` a separate interface from `Collection`?
A: Iterable was introduced in Java 1.5 to:
- Enable the enhanced
for-eachloop (for (T t : collection)) on any object — not just collections. - Allow custom, non-collection classes to be iterable by implementing
Iterable. - Cleanly separate the concern of "can be iterated" from "is a collection."
Q5: Why is `Map` not part of the `Collection` hierarchy?
A: Map stores key-value pairs, not single elements. Its structure is fundamentally different from single-element collections (List, Set, Queue). Forcing Map under Collection would break the semantic contract of the Collection interface (e.g., add(E e) doesn't make sense for a map that requires put(K key, V value)).
Q6: What are the three ways to iterate over a collection?
A:
iterator()method — returns anIteratorobject; usehasNext()+next(); supports saferemove()during iteration.- Enhanced
forloop — syntactic sugar overiterator(); clean and simple; cannot safely remove during iteration. forEach()method (Java 1.8) — takes aConsumerlambda; functional style.
Q7: How do you safely remove elements while iterating?
A: Use Iterator.remove():
1Iterator<Integer> it = list.iterator();2while (it.hasNext()) {3 Integer val = it.next();4 if (val == 3) {5 it.remove(); // Safe — no ConcurrentModificationException6 }7}list.remove() inside an enhanced for loop. It will throw ConcurrentModificationException because the collection is being modified while the underlying iterator is active.Q8: What is `ConcurrentModificationException`?
A: This exception is thrown when a collection is structurally modified (elements added or removed) while it is being iterated using an iterator, other than through the iterator's own remove() method. The collection tracks a modification count, and the iterator checks it on each step.
Q9: What is the difference between `remove(int index)` and `remove(Object o)` in a List?
A:
list.remove(2)— removes element at index 2 (primitiveint→ treated as index).list.remove(Integer.valueOf(2))— removes the first element with value2(Integer object → treated as value).
This distinction is critical when working with List.
13. Summary & Quick Revision
Revision Bullets
- JCF introduced in Java 1.2 to unify collection types under a common API.
- Problem solved: No common interface before JCF — each type had different read/write syntax.
- Iterable → root interface (Java 1.5); enables
for-eachloop andforEach()method. - Collection → extends
Iterable; root of single-element collection hierarchy (Java 1.2). - Three child interfaces of Collection:
List,Set,Queue. - Map is a separate hierarchy — not under
CollectionorIterable. - Three iteration methods:
iterator(), enhancedfor,forEach()(Java 1.8). Iterator.remove()= safe removal during iteration.Collection= interface |Collections= utility class with all-static methods.collections.remove(int)= remove by index |collections.remove(Integer)= remove by value.- Streams (
stream(),parallelStream()) added in Java 1.8 — covered separately.
14. Practice Questions
Easy
- What package contains the Java Collection Framework?
- Which interface is the root of the JCF collection hierarchy?
- What does
size()return on a collection? - What does
isEmpty()return if a collection has elements? - What Java version introduced the
forEach()method? - Write code to create an
ArrayListof Strings and add three names to it. - What is the difference between
collection.remove(2)andcollection.remove(Integer.valueOf(2))?
Medium
- Explain the three ways to iterate a collection with code examples for each.
- Why does using
list.remove()inside an enhanced for loop throwConcurrentModificationException? - What is the difference between
Collection(interface) andCollections(class)? - Write code that uses
Iteratorto remove all even numbers from aList. - Explain why
Mapis not part of theCollectionhierarchy. - What are
containsAll()andremoveAll()? Provide a code example. - What is a utility class? Why is
Collectionsconsidered one?
Hard
- If both
CollectionandIterableexisted since their respective versions, why would a class implementIterabledirectly instead ofCollection? Give a real-world use case. - Write a generic method that accepts any
Collectionand returns the sum of all elements. - Explain the internal modification count mechanism that causes
ConcurrentModificationException. How doesIterator.remove()avoid triggering it? - Why does the enhanced
forloop work on arrays even though arrays don't implementIterable? (Hint: research how the Java compiler handles arrays in for-each.) - Design a custom class
NumberRangethat implementsIterableso thatfor (int n : new NumberRange(1, 5))prints 1 through 5. Write the full implementation. - Discuss the trade-offs between using
iterator()with manualhasNext()/next()vs.forEach()with a lambda in terms of readability, performance, and capability.
ArrayList, LinkedList, Stack, PriorityQueue, ArrayDeque, HashSet, LinkedHashSet, TreeSet — will each be covered in dedicated sections explaining their internal workings, time complexities, and when to choose each one. After that, the Map hierarchy and the Streams API (Java 1.8) will be covered in detail.Practice & Implement
Apply what you learned in Collection Framework
Count frequency of each character in "programming" using a HashMap. Print as 'char: count' sorted alphabetically.
a: 1 g: 2 i: 1 m: 2 n: 1 o: 1 p: 1 r: 2
Mastery check
How well can you recall this?
Finished this lesson?