Skip to lesson

The collection family tree

The Collections Framework is a family tree of interfaces that say what a collection can do, and classes that do the actual work. Iterable is at the top, Collection comes next, and List, Set and Queue branch out from it, while Map has a tree of its own.

Interfaces describe, classes do the work

An implementation class is a class that keeps the promise of an interface, like ArrayList for List. The interface says what can be done; the class does the work.

An interface is a promise: a list of methods a class must have. List promises add, get and remove, and the classes ArrayList and LinkedList keep that promise in different ways.

Example 1 · One interface, two behaviours

OneInterfaceDemo.javaJava
import java.util.ArrayList;import java.util.Collection;import java.util.LinkedHashSet;
public class OneInterfaceDemo {    public static void main(String[] args) {        Collection<String> list = new ArrayList<>();        Collection<String> set = new LinkedHashSet<>();
        String[] orders = {"Laptop", "Mouse", "Laptop", "Keyboard"};        for (String product : orders) {            boolean inList = list.add(product);            boolean inSet = set.add(product);            System.out.println(product + " -> list: " + inList + ", set: " + inSet);        }        System.out.println("List: " + list + ", size " + list.size());        System.out.println("Set:  " + set + ", size " + set.size());        System.out.println("Set has Mouse? " + set.contains("Mouse"));    }}
Output
Laptop -> list: true, set: true
Mouse -> list: true, set: true
Laptop -> list: true, set: false
Keyboard -> list: true, set: true
List: [Laptop, Mouse, Laptop, Keyboard], size 4
Set:  [Laptop, Mouse, Keyboard], size 3
Set has Mouse? true

What this code does

  • Both variables have the type Collection<String>, so both offer the same methods: add, size(), contains. The code that calls them is identical.
  • The behaviour comes from the class. The list keeps the second Laptop; the set refuses it, and add returns false. LinkedHashSet is a set that remembers insertion order; the Sets module covers it.

You create objects only from classes, never from interfaces. So new ArrayList<>() is fine, but new List<>() is a compile error.

The tree: Iterable and Collection

Iterable is the top interface: anything Iterable works in a for-each loop. The Collection interface extends it and adds add, remove, contains, size(), isEmpty() and clear() for every group of elements.

Each level of the tree adds methods to the one above it. List, Set and Queue all extend Collection, so they all get its methods.

The collection family tree: Iterable on top, then Collection, then List, Set and Queue (Deque under Queue), each with its classes such as ArrayList, HashSet and ArrayDeque. Map is a separate tree, not a Collection, with HashMap, LinkedHashMap and TreeMap.

Example 2 · Where each class sits in the tree

FamilyTreeDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Collection;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Queue;
public class FamilyTreeDemo {    public static void main(String[] args) {        ArrayList<String> names = new ArrayList<>();        System.out.println("ArrayList is a List:       " + (names instanceof List));        System.out.println("ArrayList is a Collection: " + (names instanceof Collection));        System.out.println("ArrayList is an Iterable:  " + (names instanceof Iterable));
        ArrayDeque<String> tickets = new ArrayDeque<>();        System.out.println("ArrayDeque is a Queue:     " + (tickets instanceof Queue));        System.out.println("ArrayDeque is a List:      " + (tickets instanceof List));
        HashMap<String, Integer> fees = new HashMap<>();        System.out.println("HashMap is a Map:          " + (fees instanceof Map));        System.out.println("HashMap is a Collection:   " + (fees instanceof Collection));    }}
Output
ArrayList is a List:       true
ArrayList is a Collection: true
ArrayList is an Iterable:  true
ArrayDeque is a Queue:     true
ArrayDeque is a List:      false
HashMap is a Map:          true
HashMap is a Collection:   false

What this code does

  • instanceof answers "IS-A" questions, just as in OOP. An ArrayList is a List, so it is also a Collection and an Iterable, all the way up the tree.
  • ArrayDeque is in the Queue branch, not the List branch. A HashMap is a Map but not a Collection: maps sit in their own tree.
Do not mix up Collection (the interface) with Collections (a helper class with static methods like Collections.sort).

List, Set, Queue and Deque

A List keeps order and positions and allows duplicates. A Set refuses duplicates. A Queue hands out elements in a fixed order, usually first in, first out. A Deque is a queue that works at both ends.

These four interfaces each add one behaviour on top of Collection. Yet one method that asks for a Collection accepts a list, a set and a queue alike.

Example 3 · One method for every kind of collection

PrintAllDemo.javaJava
import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Collection;import java.util.List;import java.util.Queue;import java.util.Set;import java.util.TreeSet;
public class PrintAllDemo {    static void printAll(String title, Collection<String> items) {        System.out.print(title + " (" + items.size() + "):");        for (String item : items) {            System.out.print(" " + item);        }        System.out.println();    }
    public static void main(String[] args) {        List<String> orders = new ArrayList<>();        orders.add("Laptop");        orders.add("Mouse");        orders.add("Laptop");
        Set<String> products = new TreeSet<>(orders);   // copy, without duplicates
        Queue<String> tickets = new ArrayDeque<>();        tickets.add("T101");        tickets.add("T102");
        printAll("Orders", orders);        printAll("Products", products);        printAll("Tickets", tickets);    }}
Output
Orders (3): Laptop Mouse Laptop
Products (2): Laptop Mouse
Tickets (2): T101 T102

What this code does

  • printAll asks for a Collection<String>, so a List, a Set and a Queue can all be passed in. It works because every one of them IS-A Collection.
  • The for-each loop works on all three because Collection extends Iterable. Every collection class also has a constructor that copies another collection, as new TreeSet<>(orders) does.

Common classes: ArrayList and LinkedList for List; HashSet, LinkedHashSet and TreeSet for Set; PriorityQueue for Queue; ArrayDeque for Deque. The next lesson helps you choose between them.

Map has its own tree

A Map stores key-value pairs, like a product name and its price. Keys are unique, values may repeat, and you find a value by its key without a loop. A Map is not a Collection.

Map does not extend Collection, because its methods are different: put(key, value) and get(key) instead of add(element).

Example 4 · A Map: keys and values

PricesMapDemo.javaJava
import java.util.Collection;import java.util.Map;import java.util.Set;import java.util.TreeMap;
public class PricesMapDemo {    public static void main(String[] args) {        Map<String, Integer> prices = new TreeMap<>();        prices.put("Mouse", 800);        prices.put("Laptop", 52000);        prices.put("Keyboard", 1500);
        System.out.println(prices);        System.out.println("Keyboard costs Rs. " + prices.get("Keyboard"));
        Set<String> names = prices.keySet();        Collection<Integer> amounts = prices.values();        System.out.println("Keys:   " + names);        System.out.println("Values: " + amounts);    }}
Output
{Keyboard=1500, Laptop=52000, Mouse=800}
Keyboard costs Rs. 1500
Keys:   [Keyboard, Laptop, Mouse]
Values: [1500, 52000, 800]

What this code does

  • A map stores pairs: a key (the product name) and a value (its price). put adds a pair, and get finds a value by its key without any loop.
  • A map is not a collection, but it can give you collection views: keySet() is a Set of keys and values() is a Collection of values. TreeMap keeps keys in sorted order.

The common classes are HashMap, LinkedHashMap and TreeMap; the Maps module covers them.

A map is not Iterable, so for (String k : map) does not compile. Loop over map.keySet() or map.values() instead.

Program to the interface

Write the interface on the left of = and the class on the right: List<String> names = new ArrayList<>();. Do the same for parameters and return types.

Example 5 · Program to the interface: switch in one line

SwitchListDemo.javaJava
import java.util.ArrayList;import java.util.LinkedList;import java.util.List;
public class SwitchListDemo {    static void fillAndShow(List<String> names) {        names.add("Aarav");        names.add("Priya");        names.add(0, "Zoya");   // insert at the front        String kind = names.getClass().getSimpleName();        System.out.println(kind + ": " + names + ", first = " + names.get(0));    }
    public static void main(String[] args) {        List<String> a = new ArrayList<>();        List<String> b = new LinkedList<>();        fillAndShow(a);        fillAndShow(b);    }}
Output
ArrayList: [Zoya, Aarav, Priya], first = Zoya
LinkedList: [Zoya, Aarav, Priya], first = Zoya

What this code does

  • Both variables are declared as List<String>. Only the right side of = names the class. To change the class, you edit just that one spot.
  • fillAndShow uses only List methods, so it gives the same result for both classes. getClass().getSimpleName() shows which class the object really is.

Example 6 · Mistake: calling a class-only method through the interface

InterfaceOnlyDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class InterfaceOnlyDemo {    public static void main(String[] args) {        List<String> names = new ArrayList<>();        names.add("Aarav");        names.ensureCapacity(500);   // ArrayList has it, List does not        System.out.println(names);    }}
Sample compiler output
InterfaceOnlyDemo.java:8: error: cannot find symbol
        names.ensureCapacity(500);   // ArrayList has it, List does not
             ^
  symbol:   method ensureCapacity(int)
  location: variable names of type List<String>
1 error

What this code does

  • The compiler checks calls against the variable's type, which is List. ensureCapacity exists only in ArrayList, so the call is rejected, even though the object is an ArrayList.
  • This is the same rule as a parent reference in OOP. If you really need such a method, declare the variable as ArrayList<String>; most code never does.

This gives two wins. To change the class later, you edit one spot. And a method that asks for Collection<String> accepts any list, set or queue the caller has.

The cost is small: through a List variable you can call only List methods. The compiler checks the variable's type, exactly like a parent reference in OOP.

Fix the error

Pick the declaration that compiles

Read the real compiler error, then pick the line that fixes it.

Round 1 of 3

The cart must be read by position.

import java.util.*;
public class CartFix {
public static void main(String[] args) {
Collection<String> cart = new ArrayList<>();
cart.add("Mouse");
System.out.println(cart.get(0));
}
}

Error

CartFix.java:7: error: cannot find symbol
        System.out.println(cart.get(0));
  symbol:   method get(int)
  location: variable cart of type Collection<String>

Next step

Check your understanding

11 quick questions