The Collection Interface: Core Contract
You'll learn the five essential methods every Java collection must provide and how they form the foundation of the Collections Framework.
The Core Contract
The Collection<E> interface is the root of the collection hierarchy (excluding Map). Think of it as a contract that says: "Any class implementing me must provide these fundamental operations for managing groups of objects."
Every collection—whether it's a List, Set, or Queue—agrees to support these core methods:
The Five Pillars
boolean add(E e)– Add an element to the collectionboolean remove(Object o)– Remove a specific elementboolean contains(Object o)– Check if an element existsint size()– Return the number of elements- Iteration support – Ability to traverse all elements (via
Iterator<E> iterator())
Why This Matters
Imagine the Collection interface as a universal remote control. No matter what TV brand (specific collection type) you have, you know it has power, volume, and channel buttons. Similarly, whether you're working with an ArrayList<String>, HashSet<Integer>, or LinkedList<Double>, you can always call add(), remove(), contains(), size(), and iterate through elements.
This contract lets you write code that works with any collection:
public <E> void printSize(Collection<E> items) {
System.out.println("Size: " + items.size());
}
This method works equally well with lists, sets, or any other Collection implementation.
Key Takeaway: The Collection interface defines the core contract (add, remove, contains, size, iteration) that all collection types must honor, providing a consistent way to work with groups of objects regardless of their underlying implementation.