CodeGym /Courses /JAVA 25 SELF /Interfaces Collection, List, Set, Map: hierarchy

Interfaces Collection, List, Set, Map: hierarchy

JAVA 25 SELF
Level 27 , Lesson 0
Available

1. What is the Collection interface

In Java, an interface is like a contract: if a class implements an interface, it must provide implementations of all its methods. An interface itself does not store state and does not contain code (well, almost: starting with Java 8, default methods are possible, but the basic idea is what matters here).

Collection is the base interface for most collections in Java. It defines what a collection can do: add elements, remove them, get the size, check for the presence of elements, and so on.

public interface Collection<E> extends Iterable<E> {
    int size();
    boolean isEmpty();
    boolean contains(Object o);
    boolean add(E e);
    boolean remove(Object o);
    void clear();
    Iterator<E> iterator();
    // ... and lots of other useful methods
}

Key methods:

  • add(E e) — add an element.
  • remove(Object o) — remove an element.
  • size() — get the number of elements.
  • isEmpty() — check whether the collection is empty.
  • contains(Object o) — check for the presence of an element.
  • clear() — clear the collection.
  • iterator() — get an iterator to iterate over elements.

Why does Map not extend Collection?

Map stands apart among collections. That’s because Map is a set of “key → value” pairs, not just a set of elements. It has a different contract and a different set of methods. For example, Map has no add method, because adding is done via put(key, value), and there’s no point in checking for the presence of a value without knowing its key.

2. The collections hierarchy

A mental “tree” of the main interfaces looks like this:

                Iterable
                   |
               Collection
               /    |    \
            List   Set   Queue
                          |
                        Deque
  • Iterable — the most basic interface: anything that can be iterated over in a for-each loop.
  • Collection — extends Iterable, adds operations for working with a collection of elements.
  • Three main branches:
    • List — an ordered list, allows duplicates.
    • Set — a set of unique elements; order depends on the implementation.
    • Queue — a queue (typically FIFO); subtype — Deque (double-ended queue).

And Map lives separately:

                Map
               /   \
         HashMap  TreeMap

Hierarchy visualized (diagram)

                            +--------------------+
                            |     Iterable<E>    |
                            +--------------------+
                                     |
                            +--------------------+
                            |   Collection<E>    |
                            +--------------------+
                          /     |         \
                +--------+   +-------+   +-------+
                |  List  |   |  Set |   | Queue |
                +--------+   +-------+   +-------+
                                     |
                                  +------+
                                  |Deque |
                                  +------+

        +--------------------+
        |      Map<K,V>      |
        +--------------------+

3. List: an ordered collection with duplicates

List is a collection where:

  • The order of elements matters (first, second, third…).
  • Duplicate elements are allowed.
  • You can get an element by index (list.get(2)), replace it, or insert it anywhere.

Implementation examples: ArrayList — fast random access by index; LinkedList — good for frequent inserts/removals in the middle.

import java.util.*;

List<String> shoppingList = new ArrayList<>();
shoppingList.add("Milk");
shoppingList.add("Bread");
shoppingList.add("Cheese");
shoppingList.add("Bread"); // Duplicates are allowed!

System.out.println(shoppingList.get(1)); // "Bread"

Typical List methods:

  • add(E e), add(int index, E e)
  • get(int index), set(int index, E e)
  • remove(int index), remove(Object o)
  • indexOf(Object o), lastIndexOf(Object o)

4. Set: a set of unique elements

Set is a collection where:

  • Each element is unique (no duplicates).
  • The storage order is not guaranteed in HashSet; there may be sorting in TreeSet or insertion order in LinkedHashSet.

Implementation examples: HashSet, TreeSet, LinkedHashSet.

import java.util.*;

Set<String> uniqueNames = new HashSet<>();
uniqueNames.add("Anya");
uniqueNames.add("Boris");
uniqueNames.add("Anya"); // Won't be added — already exists!

System.out.println(uniqueNames.contains("Anya")); // true
System.out.println(uniqueNames.size()); // 2

Typical Set methods:

  • add(E e), remove(Object o)
  • contains(Object o)
  • size(), isEmpty()

5. Map: a collection of key-value pairs

Map is a collection where:

  • Each element is a key → value pair.
  • Keys are unique; values can repeat.
  • Fast access by key.

Implementation examples: HashMap, TreeMap, LinkedHashMap.

import java.util.*;

Map<String, String> phoneBook = new HashMap<>();
phoneBook.put("Anya", "+19991112233");
phoneBook.put("Boris", "+19994445566");
phoneBook.put("Anya", "+19990001122"); // Will overwrite Anya’s number!

System.out.println(phoneBook.get("Anya")); // "+19990001122"
System.out.println(phoneBook.containsKey("Boris")); // true

Typical Map methods:

  • put(K key, V value), get(K key)
  • remove(K key)
  • containsKey(K key), containsValue(V value)
  • keySet(), values(), entrySet()

6. Hierarchy visualized: all in one picture

A small summary table:

Interface Description Implementation examples Key features
List
Ordered list
ArrayList, LinkedList
Indexed access, duplicates
Set
Set of unique values
HashSet, TreeSet
Only unique elements
Map
Key–value pairs
HashMap, TreeMap
Keys are unique; values can be anything

Hierarchy on the diagram:

                Collection
                /    |    \
             List   Set   Queue
                            |
                          Deque

                Map (separately)

7. When to use which interface

List

  • When the order of elements matters (for example, a user’s action history).
  • When you need duplicates (for example, order line items).
  • When you need fast access/replacement by index.

Set

  • When you need uniqueness (emails, logins, IDs).
  • When order is unimportant, or conversely—when you need an automatically sorted set (TreeSet).

Map

  • When you need to associate keys and values (ID → object, login → profile).
  • When you need fast lookup by key.
  • When keys must be unique and values do not have to be.

8. Common mistakes when working with the collections hierarchy

Error No. 1: Using the wrong interface in the variable declaration. If you write ArrayList<String> list = new ArrayList<>();, you tie yourself tightly to the implementation. Prefer List<String> list = new ArrayList<>(); — it makes it easier to swap the implementation.

Error No. 2: Trying to add duplicates to a Set and expecting them to appear. This is not a bug but a feature: Set by definition does not store duplicates. A repeated insertion is ignored.

Error No. 3: Using Map as an ordinary collection. Map is neither a list nor a set. For iteration, use keySet(), values(), or entrySet().

Error No. 4: Expecting order in HashSet or HashMap. HashSet and HashMap do not guarantee order. If it matters—use LinkedHashSet or LinkedHashMap.

Error No. 5: Using List for unique elements. If you need uniqueness—use a Set. List does not prevent duplicates.

1
Task
JAVA 25 SELF, level 27, lesson 0
Locked
Find a color in the palette 🎨
Find a color in the palette 🎨
1
Task
JAVA 25 SELF, level 27, lesson 0
Locked
Tracking inventory in a game 🎮
Tracking inventory in a game 🎮
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION