The Collection Interface (Java)

The Collection interface is the root interface of the Java Collections Framework.
All major data structures like List, Set, and Queue are built on top of it.

It represents a group of objects, also known as elements.


Why Collection Exists?

Before Java 1.2, Java had:

  • Arrays
  • Vector
  • Hashtable

But they were inconsistent.

The Collection interface unified all data structures under a single, consistent API.


Hierarchy Overview

Collection (interface)

  • List (interface)
  • Set (interface)
  • Queue (interface)

Map does NOT extend Collection (it is separate).


Methods in the Collection Interface

The most commonly used methods are:

Basic Operations

  • add(element)
  • remove(element)
  • clear()
  • size()
  • isEmpty()

Searching

  • contains(element)

Bulk Operations

  • addAll(collection)
  • removeAll(collection)
  • retainAll(collection)

Iteration

  • iterator()

Important: Collection Works With Generics

Example:

Collection<String> names = new ArrayList<>();
names.add("Swapnil");
names.add("Java");

This ensures type safety — only Strings can be added.


Collection Doesn’t Specify Order

Collection itself does NOT define:

  • ordering
  • random access
  • sorting
  • uniqueness
  • indexing

Those are responsibilities of its sub-interfaces:

List → preserves order, allows duplicates

Set → no duplicates

Queue → insertion/removal rules


Collection + Iterator

Every Collection provides:

  • iterator()

Used to traverse elements:

Iterator<String> it = names.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}

Enhanced for-loop also works because Collection extends Iterable.


Why Collection Uses Object in contains()

contains(Object o)

Why not contains(T)?

Because:

  • The method existed before generics
  • Generics are erased at runtime (type erasure)
  • Backward compatibility
  • Before collections contains method existed with Object as param.

Result: you can pass ANY object, but equals() decides matching.


When Should You Use Collection Directly?

You rarely write:

Collection col = new ArrayList<>();

Use Collection when you want to:

  • Expose the most general behavior
  • Avoid tying API to List or Set
  • Allow any implementation to be swapped

Example:

public void printAll(Collection<String> items) {
    for (var s : items) System.out.println(s);
}

Why Map Is Not Part of Collection

Because Map stores:

  • Key/value pairs
  • Not a single group of elements

It does not fit the Collection model.


Summary

  • Collection is the root of the Java Collections Framework.
  • Defines basic operations: add, remove, contains, size, iterator.
  • Does NOT define ordering or uniqueness — List/Set/Queue do that.
  • Supports generics for type safety.
  • Works with Iterator and enhanced for-loop.