The Collections Framework
Before the Collections Framework (introduced in JDK 1.2), the standard methods for grouping Java objects (or collections) were Arrays, Vectors, and Hashtables. All of these collections had no common interface.
The Java Collections Framework provides a well-designed, unified architecture for storing and manipulating groups of objects.
Why use Collections instead of Arrays?
While Arrays are useful, they have significant limitations that the Collections Framework solves:
| Feature | Arrays | Collections |
|---|---|---|
| Size | Fixed in size (cannot grow or shrink dynamically). | Dynamic in size (grows and shrinks automatically). |
| Data Types | Can hold both primitives and Objects. | Can only hold Objects (primitives are autoboxed). |
| Built-in Methods | Very few built-in methods. | Provides ready-made methods for sorting, searching, reversing, etc. |
| Data Structures | Only linear data structures. | Provides standard structures like Sets, Queues, Lists, and Maps. |
Collections Hierarchy
The Collections Framework is primarily based on two core root interfaces: java.util.Collection and java.util.Map.
The Collection Interface
The Collection interface extends the Iterable interface (which means all its subclasses can be iterated over using a for-each loop). It is the root of:
List: An ordered collection that allows duplicates.Set: An unordered collection that does not allow duplicates.Queue: A collection used to hold elements prior to processing (typically FIFO).
The Map Interface
The Map interface is not a child of the Collection interface. It represents a mapping between a key and a value (Key-Value pairs).
Visualizing the Hierarchy
Here is a comprehensive flowchart of the Java Collections Framework.
- Dashed lines indicate interfaces.
- Solid boxes indicate concrete implementation classes.
In the next sections, we will explore the List, Set, Queue, and Map interfaces in detail, including their most popular implementation classes.