M04 · Built-in Collections

Choosing a Collection in C#, Python, Java and C++

Every standard library ships the same handful of structures under different names: a dynamic array, a hash map and set, a double-ended queue, a sorted tree and a heap. Picking the right one is mostly about asking which operations your code performs most. This lesson gives the questions, the cost table and the per-language names, and explains why the dynamic array is the default.

~35 minBeginnerC# · Python · Java · C++
Curriculum: M04 Built-in Collections · 3 of 3 lessons available

You will be able to

  • Choose a collection from the operations a task performs: by position, by key, membership, at the ends, in order, or by priority.
  • Map each abstract structure to its type in C#, Python, Java and C++, including the ones a language does not have.
  • Quote the cost of the main operations of each structure, with the case (worst, expected, amortized).
  • Explain why an array-backed list beats a linked list for most workloads despite equal O-notation.
  • Avoid the classic slow choices: removing from the front of a list, linear membership tests, legacy types.

Helpful before this lesson

  • M02 Memory Model — What a variable, a reference and a buffer really are, and why contiguous memory is fast.
  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Start from the operations

Choosing a collection is choosing which operations will be cheap. Before naming a type, list what your code does most often:

  1. Access by position? "Give me element i", "append at the end". → a dynamic array.
  2. Look up by key? "What is the price of item 42?" → a hash map.
  3. Ask "have I seen x?" → a hash set.
  4. Add or remove at the ends? A queue (FIFO) or a stack (LIFO) → a deque or a dynamic array.
  5. Need the elements in sorted order, or the nearest key to x? → a sorted (tree-based) map or set.
  6. Repeatedly take the smallest or largest? → a priority queue (heap).

Then check the secondary requirements: duplicates, iteration order, memory, and whether references to elements must stay valid while the collection changes.

The cost table

Costs below are for the standard implementations. "Expected" assumes a reasonable hash function; "amortized" is over a sequence of operations (see the best, worst, average and amortized lesson).

Structure By index Search by value Insert / remove at end At front In the middle Ordered iteration
Dynamic array O(1) O(n) amortized O(1) / O(1) O(n) O(n) insertion order
Deque (ring buffer or blocks) depends on the type (below) O(n) amortized O(1) amortized O(1) O(n) insertion order
Linked list (doubly linked) O(n) O(n) O(1) O(1) O(1) given a node, O(n) to find it insertion order
Hash map / set — expected O(1) by key expected O(1) — — unspecified (Python dict: insertion)
Sorted map / set (balanced tree) — O(log n) by key O(log n) — — sorted
Binary heap — O(n) push / pop-min O(log n), peek O(1) — — none

Indexing a deque differs by language: std::deque (C++) is O(1) everywhere; Python's collections.deque is O(1) at both ends and O(n) toward the middle; C#'s Queue<T> and Java's ArrayDeque offer no index access at all.

The names in each language

Structure C# Python Java C++
Dynamic array List<T> list ArrayList<E> std::vector<T>
Hash map Dictionary<K,V> dict HashMap<K,V> std::unordered_map
Hash set HashSet<T> set HashSet<E> std::unordered_set
Queue (FIFO) Queue<T> collections.deque ArrayDeque<E> std::queue (adaptor) over std::deque
Double-ended queue none built in (LinkedList<T>, or a custom ring buffer) collections.deque ArrayDeque<E> std::deque<T>
Stack (LIFO) Stack<T> list (append / pop) ArrayDeque<E> (push / pop) std::stack (adaptor, std::deque by default)
Priority queue PriorityQueue<E,P> (min) heapq (min) PriorityQueue<E> (min) std::priority_queue (max)
Sorted map SortedDictionary<K,V>, SortedList<K,V> none in the standard library TreeMap<K,V> std::map
Sorted set SortedSet<T> none in the standard library TreeSet<E> std::set
Insertion-ordered map OrderedDictionary<K,V> (.NET 9+) dict (guaranteed since 3.7) LinkedHashMap<K,V> none
Linked list LinkedList<T> (doubly linked) none (use deque) LinkedList<E> std::list, std::forward_list

Each linked name opens the collections encyclopedia page for that type, with every operation's cost, errors, memory effects and a tested example. The collections cheatsheet puts the same table on one page. Sorted collections are covered in the third lesson of this module.

Why the dynamic array is the default

The table makes a linked list look attractive: O(1) insertion anywhere. Two catches:

  • "Given a node." To insert at position i you first have to reach it, which is O(n). The O(1) only helps when you already hold a reference to the node, as an LRU cache does.
  • Memory layout. A dynamic array stores elements side by side; a linked list scatters nodes across the heap, each with one or two pointers of overhead. The lab above traverses both through a small teaching cache: the array loads a few cache lines and reuses each one for several elements; the list may need a new line for almost every node. Try the One-line cache preset.

Both traversals are Θ(n), and on real hardware the contiguous one is usually several times faster. That is why every language's general-purpose list is array-backed, and why the C++ Core Guidelines and most performance advice say to start with std::vector. Prefer a linked structure only when you measured a need for it, or when you need stable references to elements while others are inserted or removed. The dynamic array vs linked list comparison goes through the trade-off operation by operation.

Language notes

  • C#. There is no built-in deque; Queue<T> is a FIFO ring buffer and Stack<T> an array stack. LinkedList<T> is doubly linked and works as a deque at the cost of one node allocation per element. Dictionary enumeration order is not guaranteed; use OrderedDictionary<TKey,TValue> (.NET 9+) or a list of keys if order matters.
  • Python. list.pop(0) and list.insert(0, x) shift every element: O(n). Use collections.deque for a queue; its append, appendleft, pop and popleft are O(1), but indexing in the middle is O(n). dict preserves insertion order as a language guarantee since Python 3.7; set does not. The standard library has no sorted map or set: use bisect on a sorted list (O(log n) search, O(n) insertion) or a third-party package.
  • Java. Stack and Vector are legacy, synchronized classes; the Stack documentation itself recommends Deque implementations instead. ArrayDeque is the default for both stacks and queues (it rejects null elements). LinkedList implements both List and Deque, but get(i) walks the list.
  • C++. std::stack, std::queue and std::priority_queue are adaptors over another container. std::deque gives O(1) indexing and O(1) insertion at both ends, and does not move existing elements when it grows at the ends (references stay valid, iterators do not). std::unordered_map::operator[] inserts a default value when the key is missing; use find or contains (C++20) to only look.

Common mistakes

  • Using a list for membership tests in a loop: x in items / Contains is O(n), so a loop of them is O(n²). Build a set once.
  • Using a list as a queue by removing from the front.
  • Choosing a linked list for "fast insertion" when the code finds the position by walking from the head anyway.
  • Relying on hash map iteration order, except in Python where dict order is guaranteed.
  • Forgetting the default direction of std::priority_queue (max) when every other language's is min.
  • Reaching for a sorted collection when you only need the minimum (a heap is simpler and faster) or only need sorted output once (sort at the end).

Worked practice

1. Count how often each word occurs in a large text, then print the counts in any order. Which collection?

A hash map from word to count: Dictionary<string,int>, dict (or collections.Counter), HashMap<String,Integer> (merge(word, 1, Integer::sum)), std::unordered_map<std::string,int>. n expected-O(1) updates.

2. Same, but print the words in alphabetical order.

Either count in a hash map and sort the keys once at the end (O(n) expected + O(u log u) for u distinct words), or count directly in a sorted map (SortedDictionary, TreeMap, std::map), which costs O(log u) per update. Sorting once is usually faster; the sorted map wins if you need the order at many points along the way.

3. A breadth-first search needs a FIFO queue. What do you use in each language?

C# Queue<T>; Python collections.deque with append and popleft; Java ArrayDeque with offer and poll; C++ std::queue (over std::deque). Never a Python list with pop(0).

4. A scheduler repeatedly picks the job with the earliest deadline and adds new jobs. Which structure?

A min-priority queue keyed by deadline: O(log n) to add, O(log n) to remove the earliest. In C++ remember to pass std::greater<> (or invert the comparison), since std::priority_queue is a max-heap by default.

Summary

  • List the operations first; the dominant ones pick the structure.
  • Six structures cover most needs: dynamic array, hash map, hash set, deque, sorted tree, heap.
  • Every language has them under different names, with gaps: no deque in C#, no sorted collections in Python's standard library.
  • Prefer the dynamic array by default: contiguous memory beats linked nodes in practice.
  • Watch the traps: front removal on a list, linear membership tests, legacy Java types and the max-heap default in C++.

Full implementation

The teaching cache model in four languages, checked against one shared fixture of address streams (sequential, scattered, LRU eviction), plus each language's own layout guarantee: adjacent int[] elements in C#, a contiguous array.array buffer in Python, references in a Java ArrayList, and &v[i] == v.data() + i in C++.

using System.Runtime.CompilerServices;
 
namespace Bekadan.Dsa.Examples.Memory;
 
/// <summary>
/// Contiguous vs linked layout, and the Memory Lab's teaching cache model
/// (fixed-size lines, a few of them, least recently used evicted). The model is
/// for explaining locality, not for predicting real hardware.
/// </summary>
public static class ContiguousVsLinked
{
    /// <summary>Element i of an array starts at base + i * size.</summary>
    public static long[] ArrayAddresses(long baseAddress, int count, int elementSize)
    {
        var addresses = new long[count];
        for (int i = 0; i < count; i++)
        {
            addresses[i] = baseAddress + (long)i * elementSize;
        }
        return addresses;
    }
 
    /// <summary>A list's next address can only be read from the current node (0 = null).</summary>
    public static List<long> ListAddresses(long head, IReadOnlyDictionary<long, long> next)
    {
        var addresses = new List<long>();
        for (long node = head; node != 0;)
        {
            addresses.Add(node);
            node = next.GetValueOrDefault(node);
        }
        return addresses;
    }
 
    /// <summary>Line loads (misses) for a sequence of reads, in the teaching cache.</summary>
    public static int CountMisses(IEnumerable<long> addresses, int lineSize, int capacity)
    {
        var cache = new List<long>();  // least recently used first
        int misses = 0;
        foreach (long address in addresses)
        {
            long line = address / lineSize;
            int at = cache.IndexOf(line);
            if (at >= 0)
            {
                cache.RemoveAt(at);
                cache.Add(line);
            }
            else
            {
                misses++;
                if (cache.Count == capacity) cache.RemoveAt(0);
                cache.Add(line);
            }
        }
        return misses;
    }
 
    /// <summary>What C# itself guarantees, checked without unsafe code.</summary>
    public static void CheckLayout()
    {
        int[] values = new int[8];
        for (int i = 0; i < values.Length; i++)
        {
            Check(Unsafe.ByteOffset(ref values[0], ref values[i]) == i * sizeof(int), "int[] elements are adjacent");
        }
        var list = new LinkedList<int>([10, 20, 30]);
        LinkedListNode<int> second = list.First!.Next!;
        Check(second.Value == 20 && second.Previous == list.First, "every LinkedListNode is a separate object linked by references");
    }
 
    private static void Check(bool condition, string claim)
    {
        if (!condition) throw new InvalidOperationException($"Claim failed: {claim}");
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Memory/ContiguousVsLinked.cs

"""Contiguous vs linked layout, and the Memory Lab's teaching cache model.
 
The model (fixed-size lines, a few of them, least recently used evicted) explains
locality; it does not predict real hardware.
"""
 
from array import array
from collections.abc import Iterable
 
 
def _check(condition: bool, claim: str) -> None:
    if not condition:
        raise AssertionError(f"Claim failed: {claim}")
 
 
def array_addresses(base: int, count: int, element_size: int) -> list[int]:
    """Element i of an array starts at base + i * size."""
    addresses = []
    for i in range(count):
        addresses.append(base + i * element_size)
    return addresses
 
 
def list_addresses(head: int, nxt: dict[int, int]) -> list[int]:
    """A list's next address can only be read from the current node (0 = None)."""
    addresses = []
    node = head
    while node != 0:
        addresses.append(node)
        node = nxt.get(node, 0)
    return addresses
 
 
def count_misses(addresses: Iterable[int], line_size: int, capacity: int) -> int:
    """Line loads (misses) for a sequence of reads, in the teaching cache."""
    cache: list[int] = []  # least recently used first
    misses = 0
    for address in addresses:
        line = address // line_size
        if line in cache:
            cache.remove(line)
            cache.append(line)
        else:
            misses += 1
            if len(cache) == capacity:
                cache.pop(0)
            cache.append(line)
    return misses
 
 
def check_layout() -> None:
    """What Python itself guarantees."""
    numbers = array("i", range(8))
    view = memoryview(numbers)
    _check(view.c_contiguous and view.nbytes == len(numbers) * numbers.itemsize, "array.array keeps raw numbers in one contiguous buffer")
    shared = object()
    refs = [shared, shared]
    _check(refs[0] is refs[1], "a list stores references: the same object can sit in two slots")

Tested on CPython 3.14.0 · examples/python/dsa_examples/memory_contiguous_vs_linked.py

package dev.bekadan.dsa.memory;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
/**
 * Contiguous vs linked layout, and the Memory Lab's teaching cache model (fixed-size
 * lines, a few of them, least recently used evicted). Java exposes no addresses, and
 * the JVM decides object layout; the model explains locality, it predicts nothing.
 */
public final class ContiguousVsLinked {
    private ContiguousVsLinked() {
    }
 
    /** Element i of an array starts at base + i * size. */
    public static long[] arrayAddresses(long base, int count, int elementSize) {
        long[] addresses = new long[count];
        for (int i = 0; i < count; i++) {
            addresses[i] = base + (long) i * elementSize;
        }
        return addresses;
    }
 
    /** A list's next address can only be read from the current node (0 = null). */
    public static List<Long> listAddresses(long head, Map<Long, Long> next) {
        List<Long> addresses = new ArrayList<>();
        long node = head;
        while (node != 0) {
            addresses.add(node);
            node = next.getOrDefault(node, 0L);
        }
        return addresses;
    }
 
    /** Line loads (misses) for a sequence of reads, in the teaching cache. */
    public static int countMisses(long[] addresses, int lineSize, int capacity) {
        List<Long> cache = new ArrayList<>();   // least recently used first
        int misses = 0;
        for (long address : addresses) {
            long line = address / lineSize;
            int at = cache.indexOf(line);
            if (at >= 0) {
                cache.remove(at);
                cache.add(line);
            } else {
                misses++;
                if (cache.size() == capacity) cache.remove(0);
                cache.add(line);
            }
        }
        return misses;
    }
 
    /** An int[] holds the numbers; an ArrayList holds references to objects. */
    public static void checkLayout() {
        int[] values = {10, 20, 30};
        values[1] = 21;
        check(values[1] == 21, "an int[] element is the number itself");
        List<StringBuilder> refs = new ArrayList<>();
        StringBuilder shared = new StringBuilder("x");
        refs.add(shared);
        refs.add(shared);
        check(refs.get(0) == refs.get(1), "an ArrayList stores references: one object can sit in two slots");
    }
 
    private static void check(boolean condition, String claim) {
        if (!condition) {
            throw new AssertionError("Claim failed: " + claim);
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/memory/ContiguousVsLinked.java

#pragma once
 
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <iterator>
#include <list>
#include <unordered_map>
#include <vector>
 
namespace bekadan::dsa::memory {
 
// Contiguous vs linked layout, and the Memory Lab's teaching cache model (fixed-size
// lines, a few of them, least recently used evicted). The model explains locality;
// it does not predict real hardware.
 
// Element i of an array starts at base + i * size.
inline std::vector<std::uint64_t> array_addresses(std::uint64_t base, int count, int element_size) {
    std::vector<std::uint64_t> addresses(static_cast<std::size_t>(count));
    for (int i = 0; i < count; ++i) {
        addresses[static_cast<std::size_t>(i)] = base + static_cast<std::uint64_t>(i) * static_cast<std::uint64_t>(element_size);
    }
    return addresses;
}
 
// A list's next address can only be read from the current node (0 = nullptr).
inline std::vector<std::uint64_t> list_addresses(std::uint64_t head, const std::unordered_map<std::uint64_t, std::uint64_t>& next) {
    std::vector<std::uint64_t> addresses;
    for (std::uint64_t node = head; node != 0;) {
        addresses.push_back(node);
        const auto it = next.find(node);
        node = it == next.end() ? 0 : it->second;
    }
    return addresses;
}
 
// Line loads (misses) for a sequence of reads, in the teaching cache.
inline int count_misses(const std::vector<std::uint64_t>& addresses, std::uint64_t line_size, std::size_t capacity) {
    std::vector<std::uint64_t> cache;  // least recently used first
    int misses = 0;
    for (const std::uint64_t address : addresses) {
        const std::uint64_t line = address / line_size;
        if (const auto at = std::find(cache.begin(), cache.end(), line); at != cache.end()) {
            cache.erase(at);
            cache.push_back(line);
        } else {
            ++misses;
            if (cache.size() == capacity) cache.erase(cache.begin());
            cache.push_back(line);
        }
    }
    return misses;
}
 
// What the standard guarantees: std::vector is a contiguous container; std::list is not.
inline void check_layout() {
    std::vector<int> v(8);
    for (std::size_t i = 0; i < v.size(); ++i) assert(&v[i] == v.data() + i);
    const std::list<int> nodes{10, 20, 30};  // one allocation per node; no address relationship is promised
    assert(*std::next(nodes.begin()) == 20);
}
 
}  // namespace bekadan::dsa::memory

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/memory/contiguous_vs_linked.hpp

References