Top Banner Ad

BCS403 — Unit 4: Java Collections Framework

Table of Contents (18 sections)

BCS403 · Object Oriented Programming with Java · Unit 4

Java Collections Framework

Unit Scope & Exam Weightage: This unit covers Collection and Collection Framework, the hierarchy, Iterator, Collection, List, ArrayList, LinkedList, Vector, Stack, Queue, Set, HashSet, LinkedHashSet, SortedSet, TreeSet, Map, HashMap, LinkedHashMap, TreeMap, Hashtable, Sorting with Comparable and Comparator, and the Properties class. AKTU asks 7-mark hierarchy diagrams plus 7-mark programs on ArrayList sorting and HashMap traversal.


Importance-Wise Roadmap (BCS403 Unit 4)

Priority Exact Syllabus Topic PYQ Evidence Marks Pattern Tag
1 Hierarchy of Collection Framework 2023-24, 2024-25, 2025-26 (predicted clusters) 7m × 3 predicted Diagram mandatory
2 ArrayList + Comparator sorting 2025-26 (real) 7m Program core
3 HashMap (phone book, key/value iteration) 2023-24, 2024-25, 2025-26 (predicted clusters) 7m × 3 predicted Program core
4 LinkedList and its methods 2023-24 (real) 7m Method list
5 ArrayList vs LinkedList 2024-25 (real) 7m Comparison
6 TreeSet vs HashSet, Stack vs Queue 2025-26 / 2024-25 (real 2m each) 2m × 2 Quick marks
7 Iterator, Collection, Vector, LinkedHashSet, SortedSet, LinkedHashMap, TreeMap, Hashtable, Comparable, Properties Not directly asked Predicted Complete coverage

Collections examiner guidance: Classify each requested type first — List = ordered duplicates allowed, Set = unique, Queue = FIFO/priority retrieval, Map = key→value. Then draw the interface/implementation split; a hierarchy answer without the Map branch separate from Collection loses marks.


1. Collection Framework Hierarchy

Collection framework: a unified architecture in java.util for storing and manipulating groups of objects. It consists of interfaces (contracts such as List, Set, Queue, Map), implementations (ArrayList, HashSet, HashMap, …) and algorithms (static methods in Collections, e.g. sort, reverse, binarySearch).

Benefits: reduced programming effort (ready-made data structures), standardised behaviour, interoperability, and easier algorithm reuse. Unlike arrays, collections grow dynamically and can hold only objects — primitives are auto-boxed.

1.1 Hierarchy Diagram

                         Iterable<T>
                             |
                        Collection<T>
                 /------------+-------------\
          List<T>            Set<T>          Queue<T>
          /  |  \            /   \             |
 ArrayList LinkedList  HashSet LinkedHashSet  PriorityQueue
   Vector    \        \          \             ArrayDeque
      \       \        \          \
      Stack    \      SortedSet<T>  (Queue also implemented by LinkedList)
                          |
                        TreeSet<T>

   Map<K,V>   (separate root — does NOT extend Collection)
   /     \     \
HashMap  TreeMap LinkedHashMap
   \        \
 Hashtable  Properties

Predicted (bank PRED, 2025-26, 7 marks): "Give a detailed description of the Java Collection Framework hierarchy. Also explain the relationship between the Iterable, Collection, and List interfaces."

Stepwise answer:

  1. Iterable<T> is the root: it declares iterator() and therefore permits the enhanced for-each loop.
  2. Collection<T> extends Iterable<T> and declares common operations: add, remove, contains, size, clear, toArray.
  3. List<T> extends Collection<T>: ordered, indexable, allows duplicates; implementations ArrayList, LinkedList, Vector, Stack.
  4. Set<T> extends Collection<T>: no duplicates; HashSet, LinkedHashSet, SortedSet/TreeSet.
  5. Queue<T> extends Collection<T>: FIFO or priority retrieval; LinkedList, PriorityQueue, ArrayDeque.
  6. Map<K,V> is not a Collection: it stores key–value pairs; HashMap, LinkedHashMap, TreeMap, Hashtable.

Relationship line: every List is a Collection, and every Collection is Iterable; the reverse implications are false. A Map is Iterable only through its keySet(), values() or entrySet() views.

Predicted (bank PRED, 2024-25, 7 marks): "Discuss the hierarchy of the Collection framework in Java. Differentiate between List, Set, and Map."

Basis List Set Map
Root interface Collection Collection separate Map
Duplicates Allowed Not allowed Keys unique; values may repeat
Order Insertion/index order Depends on implementation Depends on implementation
Access By integer index By element search By key
Common classes ArrayList, LinkedList, Vector HashSet, LinkedHashSet, TreeSet HashMap, LinkedHashMap, TreeMap, Hashtable
Example [10, 10, 20] [10, 20] {roll=101, name="Aditi"}

Predicted (bank PRED, 2023-24, 7 marks): "Describe Collections framework in Java with a suitable diagram displaying interfaces and classes and their hierarchy. Also explain the List, Set and Queue interfaces." Reproduce §1.1, then: List = indexed sequence with get(i), add(i,e), remove(i); Set = uniqueness contract, add returns false for an existing element; Queue = offer, poll, peek with FIFO order, or priority order in PriorityQueue.

PYQ (2024-25, 2 marks): "How does Stack differ from Queue?"

Stack Queue
LIFO — last inserted element removed first FIFO — first inserted element removed first
push, pop, peek offer, poll, peek
Stack extends Vector Queue is a Collection interface
Example: undo history, browser back Example: printer jobs, BFS traversal

2. Iterator and the Collection Interface

2.1 Iterator Interface

Iterator: an object that traverses a collection one element at a time without exposing its internal structure. Obtained by collection.iterator().

Method Purpose
boolean hasNext() True if another element exists
E next() Returns the next element and advances
void remove() Removes the last returned element (optional)
void forEachRemaining(Consumer) Applies an action to all remaining elements
List<String> items = new ArrayList<>(List.of("Pen", "Book", "Bag"));
Iterator<String> it = items.iterator();
while (it.hasNext()) {
    String s = it.next();
    if (s.equals("Book")) it.remove();     // safe removal during iteration
}
System.out.println(items);                 // [Pen, Bag]

Iterators are fail-fast: if the collection is structurally modified by another method after iterator creation, next() throws ConcurrentModificationException. ListIterator adds backwards traversal and set/add.

2.2 Collection Interface

Collection<T> is the general contract. Key methods: add(E), addAll(Collection), remove(Object), removeIf(Predicate), contains(Object), size(), isEmpty(), clear(), iterator(), stream(), toArray(). It cannot be instantiated directly — use an implementation such as ArrayList.

Collection<Integer> c = new ArrayList<>();
c.add(5); c.add(5); c.add(7);
System.out.println(c.size() + " " + c.contains(7));   // 3 true
c.remove(5);                                          // removes one occurrence

3. List Implementations

3.1 ArrayList, LinkedList, Vector and Stack

PYQ (2024-25, 7 marks): "Compare and contrast ArrayList and LinkedList in terms of performance and usage."

Basis ArrayList LinkedList
Internal structure Dynamic resizable array Doubly linked nodes
Random access get(i) O(1) O(n) — traverses nodes
Add at end O(1) amortised (occasional resize) O(1) with tail pointer
Insert/delete in middle O(n) — shifting O(1) once the node is located
Memory Contiguous, less per-element overhead Extra next/prev references per node
Iteration Cache-friendly, usually faster Slower pointer chasing
Best for Read-heavy, indexed access Frequent head/middle insertions, deque use

Usage rule: choose ArrayList when most operations are reads by index; choose LinkedList when the workload is dominated by insertions/deletions at the ends or when both stack and queue behaviour are needed from one object.

3.2 Solved: LinkedList and Five Methods

PYQ (2023-24, 7 marks): "Describe Linked List in Java collection framework. With suitable example describe any five methods available in Linked Lists."

LinkedList<E> implements both List and Deque; each node stores data plus links to previous and next nodes.

Method Action Example result
add(E e) Appends to tail [A, B]
addFirst(E e) Inserts at head [C, A, B]
addLast(E e) Inserts at tail [C, A, B, D]
getFirst() Reads head without removing C
removeFirst() Removes and returns head C
offer(E e) Deque-style append, returns boolean true
poll() Removes head, returns null if empty next element
import java.util.*;
public class LinkedListDemo {
    public static void main(String[] args) {
        LinkedList<String> l = new LinkedList<>();
        l.add("A");                 // 1. add
        l.add("B");
        l.addFirst("C");            // 2. addFirst
        l.addLast("D");             // 3. addLast
        System.out.println(l.getFirst());   // 4. getFirst -> C
        System.out.println(l.removeFirst()); // 5. removeFirst -> C
        System.out.println(l);              // [A, B, D]
        System.out.println(l.offer("E") + " " + l.poll());
    }
}

Output:

C
C
[A, B, D]
true A

3.3 Vector and Stack

Vector is a legacy, synchronised dynamic array (similar to ArrayList but thread-safe with heavier overhead). Stack extends Vector and adds push, pop, peek, empty, search; for new code ArrayDeque is preferred because legacy Stack synchronises every operation.

Stack<Integer> s = new Stack<>();
s.push(10); s.push(20);
System.out.println(s.peek() + " " + s.pop() + " " + s);  // 20 20 [10]

3.4 Queue Interface

Queue orders elements for processing. offer inserts, poll removes, peek inspects; add/remove/element throw exceptions on failure while offer/poll/peek return false/null. PriorityQueue orders by natural order or a supplied Comparator (not FIFO); ArrayDeque is an efficient resizable array deque.

Queue<String> q = new LinkedList<>();
q.offer("Job1"); q.offer("Job2");
System.out.println(q.poll());   // Job1
System.out.println(q.peek());   // Job2

4. Set Implementations

4.1 HashSet, LinkedHashSet, SortedSet and TreeSet

Class Order Duplicate policy Complexity Implementation
HashSet Unpredictable hash order Rejects duplicates via equals/hashCode O(1) average Hash table
LinkedHashSet Insertion order Rejects duplicates O(1) average Hash table + linked list
TreeSet / SortedSet Sorted ascending by Comparable/Comparator Rejects duplicates by comparison O(log n) Red–black tree

PYQ (2025-26, 2 marks): "Why does TreeSet keep elements in sorted order, while HashSet does not?" TreeSet is a red–black self-balancing binary search tree; every insertion is placed according to compareTo (or the supplied Comparator), so an in-order walk yields sorted values. HashSet stores elements in buckets chosen by hashCode(); buckets are not ordered, so iteration order is unspecified. If insertion order is wanted without sorting, use LinkedHashSet.

Set<Integer> hs = new HashSet<>(List.of(30, 10, 20, 10));
Set<Integer> ts = new TreeSet<>(List.of(30, 10, 20, 10));
System.out.println(hs);   // e.g. [20, 10, 30] (order not guaranteed)
System.out.println(ts);   // [10, 20, 30] always sorted; duplicate 10 removed

SortedSet adds first(), last(), headSet, tailSet, subSet; NavigableSet (TreeSet) adds floor, ceiling, lower, higher, descendingSet.


5. Map Implementations

Map: an object that maps unique keys to values. It is not a Collection because it stores pairs, accessed through keySet(), values() and entrySet() views.

Class Order Null handling Notes
HashMap No order guarantee One null key, many null values Fastest average O(1); unsynchronised
LinkedHashMap Insertion (or access) order One null key Predictable iteration; useful for caches
TreeMap Sorted by key No null key (natural ordering) Red–black tree, O(log n)
Hashtable No order guarantee No nulls Legacy, synchronised; use ConcurrentHashMap today

Predicted (bank PRED, 2025-26, 7 marks): "Write a Java program that uses a HashMap to store a Phone Book (Name as key, Phone Number as value). Implement a feature to search for a number by name."

import java.util.*;
public class PhoneBook {
    public static void main(String[] args) {
        Map<String, String> book = new HashMap<>();
        book.put("Aditi", "9876543210");
        book.put("Rahul", "9123456780");
        book.put("Neha", "9988776655");
        String query = "Rahul";
        if (book.containsKey(query))
            System.out.println(query + " -> " + book.get(query));
        else
            System.out.println(query + " not found");
    }
}

Output: Rahul -> 9123456780. containsKey avoids confusing a missing entry with a stored null value.

Predicted (bank PRED, 2024-25, 7 marks): "Write a program to demonstrate the use of HashMap and iterate through keys and values."

import java.util.*;
public class HashMapIteration {
    public static void main(String[] args) {
        Map<String, Integer> marks = new HashMap<>();
        marks.put("Math", 88);
        marks.put("Java", 92);
        marks.put("OS", 79);
        System.out.println("--- keys ---");
        for (String k : marks.keySet()) System.out.println(k);
        System.out.println("--- values ---");
        for (int v : marks.values()) System.out.println(v);
        System.out.println("--- entries ---");
        for (Map.Entry<String, Integer> e : marks.entrySet())
            System.out.println(e.getKey() + " = " + e.getValue());
    }
}

Output: the three keys, then 88/92/79 in key-hash order, then three key = value lines. Use entrySet() when both parts are needed — it avoids a second lookup per entry.

Syllabus extension: Properties is a legacy Hashtable<Object,Object> for configuration strings. p.setProperty("url", "jdbc:..."), p.getProperty("url"), p.store(out, "comment") and p.load(in) read/write .properties files; XML variants use storeToXML/loadFromXML.


6. Sorting: Comparable and Comparator

Interface Method Use when
Comparable<T> compareTo(T o) One natural order per class; Collections.sort(list)
Comparator<T> compare(a,b) Several/custom orders passed to sort(list, cmp)

PYQ (2025-26, 7 marks): "Write a Java program using ArrayList to store 5 employee objects (ID, Name, Salary). Sort the list by salary in descending order using a Comparator."

import java.util.*;

class Employee {
    int id;
    String name;
    double salary;
    Employee(int id, String name, double salary) {
        this.id = id; this.name = name; this.salary = salary;
    }
    public String toString() {
        return id + " | " + name + " | " + salary;
    }
}

public class EmployeeSortDemo {
    public static void main(String[] args) {
        List<Employee> list = new ArrayList<>();
        list.add(new Employee(1, "Aditi", 62000));
        list.add(new Employee(2, "Rahul", 45000));
        list.add(new Employee(3, "Neha", 78000));
        list.add(new Employee(4, "Karan", 55000));
        list.add(new Employee(5, "Meera", 71000));

        Comparator<Employee> bySalaryDesc = (e1, e2) ->
                Double.compare(e2.salary, e1.salary);
        list.sort(bySalaryDesc);                 // Collections.sort(list, cmp) also valid

        list.forEach(System.out::println);
    }
}

Output:

3 | Neha | 78000.0
5 | Meera | 71000.0
1 | Aditi | 62000.0
4 | Karan | 55000.0
2 | Rahul | 45000.0

Why Double.compare and not e2.salary - e1.salary? Subtraction with doubles can truncate to 0 for very close values and overflow for extremes; Double.compare is total and safe. Reversing the operands gives descending order. An equivalent modern form is Comparator.comparingDouble(e -> e.salary).reversed().


7. Exam-Ready Question Index and Practice

Question (source) Solution section
Collection hierarchy + Iterable/Collection/List (2025-26, 7m predicted) §1.1
Hierarchy + List/Set/Map (2024-25, 7m predicted) §1.1 table
Framework diagram + List/Set/Queue (2023-24, 7m predicted) §1.1 + §3.4 + §4.1
Stack vs Queue (2024-25, 2m real) §1 table
ArrayList vs LinkedList (2024-25, 7m real) §3.1
LinkedList + five methods (2023-24, 7m real) §3.2
TreeSet vs HashSet (2025-26, 2m real) §4.1
Employee sort by salary descending (2025-26, 7m real) §6
Phone book HashMap (2025-26, 7m predicted) §5
Iterate keys and values (2024-25, 7m predicted) §5

Practice questions (label: practice, not real PYQs)

  1. Practice: Store five names in a TreeSet and print them; then repeat with LinkedHashSet and compare output order.
  2. Practice: Implement Comparable<Student> by roll number and sort an ArrayList with Collections.sort.
  3. Practice: Demonstrate remove() on an Iterator and show why calling list.remove() inside the same loop fails.
  4. Practice: Build a PriorityQueue<Integer> and print poll() results to show natural priority ordering.
  5. Practice: Load a .properties file with Properties.load and display one value with getProperty.

8. Last-Night Survival Checklist (Unit 4 only)

  1. Root split: Iterable → Collection → {List, Set, Queue}; Map is separate and viewed through keySet, values, entrySet.
  2. Choice rule: ArrayList = fast indexed reads; LinkedList = fast end/middle edits; HashSet = unique + fast; TreeSet = unique + sorted; HashMap = key lookup; TreeMap = sorted keys.
  3. Method pairs: Stack push/pop/peek (LIFO) vs Queue offer/poll/peek (FIFO); Iterator hasNext/next/remove.
  4. Two programs memorised: salary-descending comparator output 78000, 71000, 62000, 55000, 45000; HashMap entry traversal with Map.Entry.
  5. Sorting trap: Comparable.compareTo is natural order, Comparator.compare is external order; Double.compare beats subtraction.

Final collections reminder: In a hierarchy question, label interfaces as dashed/rounded boxes and implementation classes as concrete boxes; show Map outside the Collection branch. In a program question, print the final collection so the examiner can verify the comparator or traversal instantly.