Java Collection Framework: Complete Guide with Examples
The Java Collection Framework (JCF) is a set of classes and interfaces used to store and manipulate groups of objects dynamically. It provides efficient data structures and algorithms.
What is Collection Framework?
A collection is a group of individual objects treated as a single entity. Java provides Collection Framework to overcome limitations of arrays.
- Dynamic size (growable)
- Can store heterogeneous objects
- Provides built-in methods
Collection Interface
The Collection interface is the root interface of Collection Framework.
Important Methods
add()remove()size()clear()
List Interface
List is an ordered collection that allows duplicates.
- Insertion order preserved
- Duplicates allowed
Implementations
- ArrayList
- LinkedList
- Vector
Example
import java.util.*;
List list = new ArrayList();
list.add(10);
list.add("Java");
System.out.println(list);
Set Interface
Set does not allow duplicate elements.
- No duplicates
- Insertion order not guaranteed
Implementations
- HashSet
- LinkedHashSet
- TreeSet
Example
Set set = new HashSet();
set.add(10);
set.add(10);
System.out.println(set); // duplicate removed
Queue Interface
Queue follows FIFO (First In First Out).
- PriorityQueue
Example
Queue q = new PriorityQueue();
q.add(10);
q.add(5);
System.out.println(q);
Map Interface
Map stores data in key-value pairs.
- Keys → unique
- Values → duplicates allowed
Implementations
- HashMap
- LinkedHashMap
- TreeMap
- Hashtable
Example
Map map = new HashMap();
map.put(1, "Java");
map.put(2, "Spring");
System.out.println(map);
Cursors in Java
Cursors are used to retrieve objects one by one from collections.
Types
- Enumeration (legacy)
- Iterator
- ListIterator
Example
Iterator it = list.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
Collection Framework Summary
- Collection → root interface
- List → ordered, duplicates allowed
- Set → no duplicates
- Queue → FIFO
- Map → key-value pairs
Collection Framework FAQ
What is Collection Framework?
A set of classes and interfaces to manage data efficiently.
Difference between List and Set?
List allows duplicates, Set does not.
Difference between HashMap and Hashtable?
HashMap is not synchronized, Hashtable is thread-safe.