← Back to Courses
Β© 2025 sampathirao yoganandh
Week 13 Β· CO-4

Collection Framework β€” Interfaces

Collection, List, Set, Queue, and Map interfaces; Iterator  CO-4

What is the Collection Framework?

The Java Collections Framework provides a unified architecture for representing and manipulating groups of objects. It includes:

Hierarchy:
Iterable
  └── Collection
        β”œβ”€β”€ List      β†’ ArrayList, LinkedList, Vector, Stack
        β”œβ”€β”€ Set       β†’ HashSet, LinkedHashSet, TreeSet
        └── Queue     β†’ PriorityQueue, ArrayDeque, LinkedList

Map (separate hierarchy)
  β”œβ”€β”€ HashMap, LinkedHashMap
  └── SortedMap β†’ TreeMap
πŸ“Œ Key PointBy default, collections hold heterogeneous objects (any type). Use Generics (e.g., List<String>) to restrict to a single type and get type safety.

Collection Interface

The root interface of the collection hierarchy. All collection types implement it. Key methods:

MethodDescription
add(E e)Adds element e
remove(Object o)Removes specified element
size()Returns number of elements
isEmpty()Returns true if collection has no elements
contains(Object o)Returns true if element is present
iterator()Returns an Iterator over elements
clear()Removes all elements
toArray()Converts collection to array

List Interface

List is an ordered, index-based collection that allows duplicates.

MethodDescription
get(int index)Returns element at index
set(int index, E e)Replaces element at index
add(int index, E e)Inserts at specific position
remove(int index)Removes element at index
indexOf(Object o)Returns first index of element
subList(from, to)Returns a view of portion [from, to)
import java.util.*;

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add(0, "Zara");       // insert at front
names.set(1, "Arjun");       // replace index 1
System.out.println(names);     // [Zara, Arjun, Bob]
System.out.println(names.get(2)); // Bob

Set Interface

Set is a collection that does not allow duplicates. Order depends on implementation.

ImplementationOrderingNull allowedPerformance
HashSetNo guaranteed orderOne nullO(1) avg
LinkedHashSetInsertion orderOne nullO(1) avg
TreeSetSorted (natural/comparator)No nullO(log n)
Set<String> fruits = new HashSet<>();
fruits.add("Apple");
fruits.add("Mango");
fruits.add("Apple"); // duplicate β€” ignored
System.out.println(fruits.size()); // 2

Queue Interface

Queue follows FIFO (First-In-First-Out) ordering. Key methods:

MethodThrows exception?Returns special value?
add(e) / offer(e)add() throws, offer() returns falseoffer() returns false
remove() / poll()remove() throws, poll() returns nullpoll() returns null if empty
element() / peek()element() throws, peek() returns nullpeek() returns null if empty
Queue<String> queue = new LinkedList<>();
queue.offer("Task 1");
queue.offer("Task 2");
queue.offer("Task 3");
System.out.println(queue.peek());  // Task 1 (doesn't remove)
System.out.println(queue.poll());  // Task 1 (removes)
System.out.println(queue.size());  // 2

Map Interface

Map stores key-value pairs. Keys are unique; values can be duplicated. Map does NOT extend Collection.

MethodDescription
put(K,V)Adds key-value pair; overwrites if key exists
get(K)Returns value for key, or null
remove(K)Removes entry by key
containsKey(K)true if key exists
keySet()Returns Set of all keys
values()Returns Collection of all values
entrySet()Returns Set of Map.Entry pairs
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
scores.put("Bob", 88);
scores.put("Alice", 99); // overwrites Alice's score

for (Map.Entry<String,Integer> e : scores.entrySet())
    System.out.println(e.getKey() + " β†’ " + e.getValue());

Iterator

Iterator provides a safe way to traverse collections and remove elements during iteration.

List<Integer> nums = new ArrayList<>(Arrays.asList(1,2,3,4,5));
Iterator<Integer> it = nums.iterator();

while (it.hasNext()) {
    int n = it.next();
    if (n % 2 == 0)
        it.remove(); // safe removal during iteration
}
System.out.println(nums); // [1, 3, 5]
⚠️ ImportantNever modify a collection using list.remove() directly while iterating with an iterator β€” it throws ConcurrentModificationException. Always use it.remove().
πŸ“„

Download PDF Notes

Save these notes as a PDF for offline reference

View / Download PDF