Collection Hierarchy

Basic Java
≈ 2 min read

A common interface for different structures

Most Java collections are connected through a common system of interfaces. This lets code depend not on a concrete class, but on the set of capabilities it actually needs. At the center of this system is the Collection<E> interface.

It describes basic operations on a group of elements: add a value, remove it, check whether it is present, get the size, or clear the collection. Specific branches add their own rules to these operations.

Collection<String> names = new ArrayList<>();
names.add("Ann");
names.add("Bob");

System.out.println(names.contains("Ann"));
System.out.println(names.size());

The main branches

  • List<E> — an ordered sequence in which elements may repeat.
  • Set<E> — a set of unique elements.
  • Queue<E> — a structure for processing elements in a particular order.
  • Deque<E> — a queue that can be accessed from both ends.

These interfaces do not define a concrete internal structure. For example, a variable of type List<String> can refer to different list implementations. That is useful: the rest of the code depends on List behavior rather than on details of a particular class.

Where is Map?

Map<K, V> belongs to the Collections Framework, but it does not extend Collection. The reason is its data model: an ordinary collection stores individual elements, while a Map stores key-value pairs.

A map therefore has its own core operations: put a value under a key, retrieve it, check whether a key exists, or remove a pair. We will study this branch separately.

Try to declare a variable through the interface you need. If the code only needs List capabilities, it is usually better to write List<String> names = new ArrayList<>(); rather than tie the variable to ArrayList unnecessarily.