Collections Framework
TL;DR
- The Java Collections Framework (JCF) is a unified architecture for storing and manipulating groups of objects.
- It provides high-performance, high-quality implementations of common data structures (lists, sets, maps, queues).
- Core Interfaces:
Iterable,Collection,List,Set,Queue, andMap.
Concept
Before the Collections Framework (introduced in Java 1.2), developers had to use arrays, Vector, or Hashtable. There was no common interface, making it difficult to switch between different data structures.
The JCF standardizes the way groups of objects are handled. It provides:
- Interfaces: Abstract data types representing collections (
List,Set,Map). - Implementations: Concrete classes of the interfaces (
ArrayList,HashSet,HashMap). - Algorithms: Polymorphic methods that perform useful computations on objects that implement collection interfaces (e.g., sorting, searching).
Examples
import java.util.*;
public class CollectionsFrameworkExample {
public static void main(String[] args) {
// Programming to an Interface
List<String> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
Map<String, String> map = new HashMap<>();
Queue<Double> queue = new PriorityQueue<>();
// Using common algorithms provided by the framework
list.add("Zebra");
list.add("Apple");
list.add("Monkey");
System.out.println("Before sorting: " + list);
Collections.sort(list); // Framework Algorithm
System.out.println("After sorting: " + list);
}
}
Interview Questions
Q: What is the root interface of the Java Collections Framework?
A: Technically, it is java.lang.Iterable. The Collection interface extends Iterable. Note that the Map interface is not a descendant of Collection or Iterable, but it is still considered part of the Java Collections Framework.
Q: What are the main benefits of using the Collections Framework?
A: 1. Reduces programming effort: Provides out-of-the-box data structures and algorithms.
2. Increases performance: Highly optimized implementations.
3. Fosters software reuse: A common API allows different APIs to interoperate seamlessly (e.g., methods returning a Collection instead of a specific array type).