Programming Search⌘K

Conceptcore

Collection interfaces

Also called collection hierarchy, Iterable, Collection interface, Sequence and Mapping, collections.abc, IEnumerable, ICollection, programming to the interface.

Collection interfaces such as Iterable, Collection, Sequence and Mapping name what a kind of collection can do. Code written to the interface works with each class that implements it.

Applies to
core-languages

Idea

A function that adds up some numbers does not care whether they come in a list, a set or the values of a map. It needs only one operation: give me the numbers one by one. A function that reports the size needs one more: tell me how many there are. Collection interfaces give names to these sets of operations. The weakest interface asks for the least, and more of the collections in the program pass it.

from collections.abc import Collection, Iterable, Mapping, Sequence


def total(xs: Iterable[int]) -> int:      # needs only a loop
    return sum(xs)


def describe(c: Collection[int]) -> str:  # needs a loop, len and in
    return f"size {len(c)}, total {total(c)}, has 3: {3 in c}"


prices = {"tea": 3, "cake": 4}
for c in ([1, 2, 3], {4, 5}, prices.values()):
    print(type(c).__name__, describe(c))

print(total(n * n for n in range(4)))     # a generator is Iterable only
print(isinstance([], Sequence), isinstance(prices, Mapping), isinstance({4}, Sequence))
Output
list size 3, total 6, has 3: True
set size 2, total 9, has 3: False
dict_values size 2, total 7, has 3: True
14
True True False

total takes any iterable, so it works with a generator too. describe takes a Collection, so it can call len and use in, but a generator does not pass. The isinstance tests show the finer interfaces: a list is a Sequence, a dict is a Mapping, and a set is not a Sequence.

How it works

A hierarchy of interfaces. In Java, "The core collection interfaces encapsulate different types of collections"1, and "These interfaces allow collections to be manipulated independently of the details of their representation"1. They "form a hierarchy"1: Collection is "The root interface in the collection hierarchy"2, List, Set and Queue extend it, and SortedSet extends Set. Each level adds operations. Most languages have the same three levels:

  • an iterable: the elements can be visited one by one;
  • a collection: the elements can also be counted and tested for membership;
  • a sequence, a set or a map: each adds its own operations, such as access by index, set algebra or lookup by key.

Python: abstract base classes. The module collections.abc gives the levels as classes. Iterable needs __iter__. Collection inherits from Sized, Iterable and Container, so it needs __len__, __iter__ and __contains__3. Sequence, Set and Mapping inherit from Collection, and each has a mutable form: MutableSequence, MutableSet and MutableMapping3. A class that inherits from one of them writes the abstract methods and gets the rest: "The remaining mixin methods come from inheritance and can be overridden if desired"3.

C# and Kotlin. In .NET, IEnumerable<T> "Exposes the enumerator, which supports a simple iteration over a collection of a specified type"4. "The ICollection interface extends IEnumerable; IDictionary<TKey,TValue> and IList are more specialized interfaces that extend ICollection"5. .NET also has a read-only family: IReadOnlyCollection<T> "Represents a strongly-typed, read-only collection of elements"6, and IReadOnlyList<T> and IReadOnlyDictionary<TKey,TValue> build on it. In Kotlin, "Collection is the common superinterface of List and Set"7, and "Each main collection type has a read-only interface, such as List, and a corresponding mutable interface, such as MutableList"7.

Rust, Go and C++: smaller pieces. Rust has no Collection trait. It has a trait for each ability. A for loop works with any type that implements IntoIterator, and "This trait has one method, into_iter, which converts the thing implementing IntoIterator into an iterator"8. FromIterator is the other direction: "By implementing FromIterator for a type, you define how it will be created from an iterator"9. Go has no collection interfaces. Its iter package defines Seq, "an iterator over sequences of individual values"10, and functions in the library give a Seq for the built-in collections: "maps.Keys returns an iterator over the keys of a map"10. In TypeScript and JavaScript, "An object is deemed iterable if it has an implementation for the Symbol.iterator property"11. C++ writes its interfaces as requirements on template arguments, not as base classes: "A Container is an object used to store other objects and taking care of the management of the memory used by the objects it contains"12.

Programming to the interface. A parameter, a field or a return type should name the weakest interface that the code needs. "The Collection interface is used to pass around collections of objects where maximum generality is desired"13. For example, each general-purpose Java collection has a constructor that takes a Collection. "This constructor, known as a conversion constructor, initializes the new collection to contain all of the elements in the specified collection, whatever the given collection's subinterface or implementation type"13. The caller can then pass a list, a set or a queue.

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaStandard library
CAbsent
C#Standard library
JavaScriptNative
TypeScriptNative
GoStandard library
RustStandard library
KotlinStandard libraryKotlin has Iterable, Collection, List, Set and Map, each with a Mutable form. Map does not extend Collection. No example file exists because kotlinc is not installed.
SQLDoes not applyA query works on tables, not on collection interfaces.
BashAbsent
PowerShellStandard libraryPowerShell can use the .NET interfaces, such as IEnumerable and ICollection. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no collections in program code.
CSSDoes not applyCSS has no collections in program code.
Regular expressionsDoes not applyA regular expression has no collections.
Language Verdict Mechanism
Python stdlib collections.abc: Iterable, Collection, Sequence, Set, Mapping and their mutable forms
JavaScript native the iterable protocol (Symbol.iterator); no interface names
TypeScript native Iterable<T>, ReadonlyArray<T>, ReadonlySet<T>, ReadonlyMap<K, V> as structural types
Java stdlib Iterable, Collection, List, Set, Queue, Deque, Map in java.lang and java.util
Kotlin stdlib Iterable, Collection, List, Set, Map and the Mutable forms
C# stdlib IEnumerable<T>, ICollection<T>, IList<T>, IDictionary<TKey,TValue> and the IReadOnly forms
Go stdlib no collection interfaces; iter.Seq and iter.Seq2 for iteration
Rust stdlib traits for each ability: IntoIterator, FromIterator, Extend, Index
C absent no interfaces; a library can use a struct of function pointers
C++ stdlib named requirements and concepts, such as std::ranges::range, checked on templates
Bash absent no interfaces; arrays only
PowerShell stdlib the .NET interfaces, such as IEnumerable and ICollection
SQL n/a a query works on tables, not on collection interfaces
Regex n/a a pattern has no collections
HTML n/a HTML has no collections in program code
CSS n/a CSS has no collections in program code

Java, C#, Kotlin and Python have a full hierarchy of named interfaces. TypeScript has the same ideas as structural types, so a class needs no implements clause to match. Rust and C++ check the abilities at compile time through traits and concepts, and Go asks only for an iterator. C and Bash have no way to name a collection interface.

The example files write two functions in each language: total, which needs only iteration, and describe, which also needs the size. Each file calls them with a list, a set and the values of a map. Python uses collections.abc. JavaScript passes any iterable. TypeScript uses Iterable<number> and ReadonlySet<number>. Java uses Iterable<Integer> and Collection<Integer>. C# uses IEnumerable<int> and IReadOnlyCollection<int>. Go uses iter.Seq[int]. Rust uses IntoIterator and ExactSizeIterator. C++ uses the concepts std::ranges::input_range and std::ranges::sized_range. C and Bash have no interfaces, so their files show the usual workaround: a struct of function pointers in C, and a function that takes the name of an array in Bash.

PythonGitHub
from collections.abc import Collection, Iterable, Iterator, Sized


def total(xs: Iterable[int]) -> int:
    return sum(xs)


def describe(c: Collection[int]) -> str:
    return f"size {len(c)}, total {total(c)}"


class Countdown:
    """A collection class: three methods give it the Collection interface."""

    def __init__(self, n: int) -> None:
        self._n = n

    def __len__(self) -> int:
        return self._n

    def __iter__(self) -> Iterator[int]:
        return iter(range(self._n, 0, -1))

    def __contains__(self, x: object) -> bool:
        return isinstance(x, int) and 0 < x <= self._n


print("list:", describe([1, 2, 3]))
print("set:", describe({4, 5}))
print("map values:", describe({"tea": 3, "cake": 4}.values()))
print(isinstance(Countdown(3), Collection), describe(Countdown(3)))
print(isinstance(iter([1]), Sized))
Output
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7
True size 3, total 6
False
  • Verdict: stdlib. collections.abc has Iterable, Collection, Sequence, Set, Mapping and their mutable forms.
  • Countdown does not inherit from Collection, but isinstance says yes, because the class has __len__, __iter__ and __contains__.
  • An iterator is Iterable but not Sized, so describe would not accept it.
#include <iostream>
#include <map>
#include <numeric>
#include <ranges>
#include <set>
#include <string>
#include <vector>

int total(std::ranges::input_range auto&& xs) {
    int sum = 0;
    for (int x : xs) sum += x;
    return sum;
}

std::string describe(std::ranges::sized_range auto&& c) {
    return "size " + std::to_string(std::ranges::size(c)) + ", total " + std::to_string(total(c));
}

int main() {
    std::vector<int> list{1, 2, 3};
    std::set<int> set{4, 5};
    std::map<std::string, int> prices{{"tea", 3}, {"cake", 4}};

    std::cout << "list: " << describe(list) << '\n';
    std::cout << "set: " << describe(set) << '\n';
    std::cout << "map values: " << describe(prices | std::views::values) << '\n';
}
Output
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7
  • Verdict: stdlib. C++ names collection interfaces as concepts, such as std::ranges::input_range and std::ranges::sized_range, and as named requirements such as Container. The compiler checks them on template arguments.
  • prices | std::views::values is a view of the values of the map. It is a sized range, so describe takes it.
JavaGitHub
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class Main {
    static int total(Iterable<Integer> xs) {
        int sum = 0;
        for (int x : xs) sum += x;
        return sum;
    }

    static String describe(Collection<Integer> c) {
        return "size " + c.size() + ", total " + total(c);
    }

    public static void main(String[] args) {
        Map<String, Integer> prices = new TreeMap<>(Map.of("tea", 3, "cake", 4));
        System.out.println("list: " + describe(List.of(1, 2, 3)));
        System.out.println("set: " + describe(new TreeSet<>(Set.of(4, 5))));
        System.out.println("map values: " + describe(prices.values()));

        ArrayDeque<Integer> copy = new ArrayDeque<>(prices.values()); // conversion constructor
        System.out.println(copy + " " + (prices instanceof Collection<?>));
    }
}
Output
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7
[4, 3] false
  • Verdict: stdlib. Iterable is in java.lang, and Collection, List, Set, Queue, Deque and Map are in java.util.
  • describe takes a Collection<Integer>, so a list, a set and the values() view of a map all pass.
  • A Map is not a Collection. The TreeMap orders its keys, so the values come as cake then tea.
#include <stddef.h>
#include <stdio.h>

/* An interface by hand: a struct of function pointers and a context. */
struct int_collection {
    size_t (*size)(const void *self);
    int (*get)(const void *self, size_t i);
    const void *self;
};

struct array {
    const int *items;
    size_t len;
};

static size_t array_size(const void *self) { return ((const struct array *)self)->len; }
static int array_get(const void *self, size_t i) { return ((const struct array *)self)->items[i]; }

static void describe(const char *name, struct int_collection c) {
    int sum = 0;
    size_t n = c.size(c.self);
    for (size_t i = 0; i < n; i++) {
        sum += c.get(c.self, i);
    }
    printf("%s: size %zu, total %d\n", name, n, sum);
}

int main(void) {
    const int list[] = {1, 2, 3};
    struct array a = {list, 3};
    describe("list", (struct int_collection){array_size, array_get, &a});
    return 0;
}
Output
list: size 3, total 6
  • Verdict: absent. C has no interfaces and no standard collections. A library can define its own interface as a struct of function pointers, as this example does, and each collection type fills in the pointers.
using System;
using System.Collections.Generic;

static int Total(IEnumerable<int> xs)
{
    int sum = 0;
    foreach (var x in xs) sum += x;
    return sum;
}

static string Describe(IReadOnlyCollection<int> c) => $"size {c.Count}, total {Total(c)}";

var prices = new Dictionary<string, int> { ["tea"] = 3, ["cake"] = 4 };
Console.WriteLine("list: " + Describe(new List<int> { 1, 2, 3 }));
Console.WriteLine("set: " + Describe(new HashSet<int> { 4, 5 }));
Console.WriteLine("map values: " + Describe(prices.Values));

IEnumerable<int> squares = Squares(4);
Console.WriteLine($"{Total(squares)} {squares is IReadOnlyCollection<int>}");

static IEnumerable<int> Squares(int n)
{
    for (int i = 0; i < n; i++) yield return i * i;
}
Output
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7
14 False
  • Verdict: stdlib. System.Collections.Generic has IEnumerable<T>, ICollection<T>, IList<T>, IDictionary<TKey,TValue> and the read-only forms IReadOnlyCollection<T>, IReadOnlyList<T> and IReadOnlyDictionary<TKey,TValue>.
  • List<T>, HashSet<T> and the Values of a Dictionary all implement IReadOnlyCollection<int>. An iterator method gives only IEnumerable<int>.
JavaScriptGitHub
function total(xs) {
  let sum = 0;
  for (const x of xs) sum += x; // any iterable
  return sum;
}

function describe(c) {
  const size = c.length ?? c.size; // no shared name for the size
  return `size ${size}, total ${total(c)}`;
}

const prices = new Map([["tea", 3], ["cake", 4]]);
console.log("list:", describe([1, 2, 3]));
console.log("set:", describe(new Set([4, 5])));
console.log("map values:", describe([...prices.values()]));
console.log(total(prices.values()), prices.values().size);
Output
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7
7 undefined
  • Verdict: native. The iterable protocol is the one shared interface: an object with a Symbol.iterator method works with for...of and the spread syntax.
  • JavaScript has no shared size interface. An array has length, a set and a map have size, and the iterator from values() has neither, so the code copies the values into an array before it calls describe.
TypeScriptGitHub
function total(xs: Iterable<number>): number {
  let sum = 0;
  for (const x of xs) sum += x;
  return sum;
}

type Sized = { readonly size: number } | { readonly length: number };

function describe(c: Iterable<number> & Sized): string {
  const size = "size" in c ? c.size : c.length;
  return `size ${size}, total ${total(c)}`;
}

const list: readonly number[] = [1, 2, 3];
const set: ReadonlySet<number> = new Set([4, 5]);
const prices: ReadonlyMap<string, number> = new Map([["tea", 3], ["cake", 4]]);

console.log("list:", describe(list));
console.log("set:", describe(set));
console.log("map values:", describe([...prices.values()]));
Output
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7
  • Verdict: native. Iterable<T>, ReadonlyArray<T>, ReadonlySet<T> and ReadonlyMap<K, V> are structural types: a value matches when it has the members, with no implements clause.
  • The read-only types have no push, add or set, so the checker stops code that takes them from changing them.
  • TypeScript has no shared size interface either, so Sized accepts size or length.
package main

import (
	"fmt"
	"iter"
	"maps"
	"slices"
)

func total(xs iter.Seq[int]) int {
	sum := 0
	for x := range xs {
		sum += x
	}
	return sum
}

func describe(size int, xs iter.Seq[int]) string {
	return fmt.Sprintf("size %d, total %d", size, total(xs))
}

func main() {
	list := []int{1, 2, 3}
	set := map[int]struct{}{4: {}, 5: {}}
	prices := map[string]int{"tea": 3, "cake": 4}

	fmt.Println("list:", describe(len(list), slices.Values(list)))
	fmt.Println("set:", describe(len(set), maps.Keys(set)))
	fmt.Println("map values:", describe(len(prices), maps.Values(prices)))
}
Output
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7
  • Verdict: stdlib. Go has no collection interfaces. iter.Seq[int] is a function type for any sequence of int values, and slices.Values, maps.Keys and maps.Values make one from a built-in collection.
  • A Seq has no size, and len works only on built-in types, so describe takes the size as a second argument.
RustGitHub
use std::collections::{BTreeMap, BTreeSet};

fn total<'a>(xs: impl IntoIterator<Item = &'a i32>) -> i32 {
    xs.into_iter().sum()
}

fn describe<'a, C>(c: &'a C) -> String
where
    &'a C: IntoIterator<Item = &'a i32>,
    <&'a C as IntoIterator>::IntoIter: ExactSizeIterator,
{
    let size = c.into_iter().len();
    format!("size {}, total {}", size, total(c))
}

fn main() {
    let list = vec![1, 2, 3];
    let set = BTreeSet::from([4, 5]);
    let prices = BTreeMap::from([("tea", 3), ("cake", 4)]);
    let values: Vec<i32> = prices.values().copied().collect(); // FromIterator

    println!("list: {}", describe(&list));
    println!("set: {}", describe(&set));
    println!("map values: {} (direct total {})", describe(&values), total(prices.values()));
}
Output
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7 (direct total 7)
  • Verdict: stdlib. Rust has no Collection trait. IntoIterator lets a type be used in a for loop, ExactSizeIterator gives the length, and FromIterator lets collect build a collection.
  • describe works with a reference to any collection whose iterator knows its length, such as Vec and BTreeSet. The compiler makes one copy of it for each type.
BashGitHub
# Bash has no interfaces. The convention: a function takes the name of an array.
describe() {
  local -n c=$1
  local sum=0 x
  for x in "${c[@]}"; do sum=$(( sum + x )); done
  echo "size ${#c[@]}, total $sum"
}

list=(1 2 3)
declare -A prices=([tea]=3 [cake]=4)
values=("${prices[@]}")

echo "list: $(describe list)"
echo "map values: $(describe values)"
Output
list: size 3, total 6
map values: size 2, total 7
  • Verdict: absent. Bash has indexed and associative arrays, and no way to name an interface. A function that takes the name of an array works with any array, by convention only.
  • Nominal and structural. In Java, C# and Kotlin, a class matches an interface only when it declares it. In TypeScript and Go, a type matches when it has the right members. Python allows both: a class can inherit from an ABC, or be registered as a virtual subclass, and some ABCs such as Iterable match any class with the right methods3.
  • Read-only interfaces. A read-only interface gives no way to change the collection. It is a promise of the code that takes the parameter, not of the collection itself. See immutability.
  • Optional operations. Java keeps one interface for each kind and makes some methods optional. "To keep the number of core collection interfaces manageable, the Java platform doesn't provide separate interfaces for each variant of each collection type"1. An unmodifiable list implements List, but its add throws an exception.
  • Iterators. The lowest level of the hierarchy is the iterator protocol, which also covers generators and streams. See iterators.

Pitfalls

  • Asking for too much. A parameter of type List or ArrayList refuses a set or a queue, even when the function only loops over its argument. Ask for Iterable or Collection, or for the read-only form.
  • A map is not a collection. In Java, "the hierarchy consists of two distinct trees"1, and a Map does not extend Collection. In Kotlin, "Map doesn't extend Collection"7. Pass keySet(), values() or entrySet() when the code needs a collection.
  • Read-only is not immutable. Another reference to the same collection can still change it. Kotlin says this plainly: "By contrast, an immutable collection doesn't allow you to change its elements after creation"7. Copy the collection, or use an immutable one, when the elements must not change.
  • An iterable that runs once. A Python generator passes the Iterable test, but a second loop over it finds nothing. A function that loops twice must ask for a Collection, or copy its argument into a list first.
  • Mixins with the wrong cost. A mixin method is correct for every class but fast only for some. In collections.abc, if __getitem__ "is linear (as it would be with a linked list), the mixins will have quadratic performance and will likely need to be overridden"3.

Cost

A call through an interface in Java, C# or Kotlin is a virtual call, because the code does not know the class of the collection. A generic function in Rust or C++ is compiled for each concrete type, so its calls through IntoIterator or a range concept are direct. See templates and generics. In Python, the ABCs cost nothing until the code tests them: they are classes "that can be used to test whether a class provides a particular interface"3, and the test runs only when the code calls isinstance or issubclass.

History

"The collections framework was designed and developed primarily by Joshua Bloch, and was introduced in JDK 1.2"14. "Core collection interfaces are the foundation of the Java Collections Framework"1. Python moved its abstract collection classes to their own module, collections.abc; before that, "this module was part of the collections module"3.

References

  1. Interfaces, The Java Tutorials (Collections), Whole page
  2. Interface Collection, Java SE 21, Interface description
  3. collections.abc, Python 3.14 documentation, Introduction; Collections Abstract Base Classes
  4. IEnumerable<T> Interface, .NET API reference, Definition
  5. ICollection<T> Interface, .NET API reference, Remarks
  6. IReadOnlyCollection<T> Interface, .NET API reference, Definition
  7. Collections overview, Kotlin documentation, Read-only and mutable collections
  8. Module std::iter, Rust standard library, for loops and IntoIterator
  9. Trait FromIterator, Rust standard library, Introduction
  10. Package iter, Go standard library, Overview; type Seq
  11. Iterators and Generators, The TypeScript Handbook, Iterables
  12. C++ named requirements, Container, cppreference.com, Introduction
  13. The Collection Interface, The Java Tutorials, Whole page
  14. Java collections framework, Wikipedia, History

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/B506TN/text.yaml