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))
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
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Absent | |
| C# | Standard library | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Standard library | |
| Rust | Standard library | |
| Kotlin | Standard library | Kotlin 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. |
| SQL | Does not apply | A query works on tables, not on collection interfaces. |
| Bash | Absent | |
| PowerShell | Standard library | PowerShell can use the .NET interfaces, such as IEnumerable and ICollection. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no collections in program code. |
| CSS | Does not apply | CSS has no collections in program code. |
| Regular expressions | Does not apply | A 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.
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))
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.abchasIterable,Collection,Sequence,Set,Mappingand their mutable forms. Countdowndoes not inherit fromCollection, butisinstancesays yes, because the class has__len__,__iter__and__contains__.- An iterator is
Iterablebut notSized, sodescribewould 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';
}
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_rangeandstd::ranges::sized_range, and as named requirements such as Container. The compiler checks them on template arguments. prices | std::views::valuesis a view of the values of the map. It is a sized range, sodescribetakes it.
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<?>));
}
}
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7
[4, 3] false
- Verdict: stdlib.
Iterableis injava.lang, andCollection,List,Set,Queue,DequeandMapare injava.util. describetakes aCollection<Integer>, so a list, a set and thevalues()view of a map all pass.- A
Mapis not aCollection. TheTreeMaporders its keys, so the values come ascakethentea.
#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;
}
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;
}
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7
14 False
- Verdict: stdlib.
System.Collections.GenerichasIEnumerable<T>,ICollection<T>,IList<T>,IDictionary<TKey,TValue>and the read-only formsIReadOnlyCollection<T>,IReadOnlyList<T>andIReadOnlyDictionary<TKey,TValue>. List<T>,HashSet<T>and theValuesof aDictionaryall implementIReadOnlyCollection<int>. An iterator method gives onlyIEnumerable<int>.
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);
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.iteratormethod works withfor...ofand the spread syntax. - JavaScript has no shared size interface. An array has
length, a set and a map havesize, and the iterator fromvalues()has neither, so the code copies the values into an array before it callsdescribe.
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()]));
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7
- Verdict: native.
Iterable<T>,ReadonlyArray<T>,ReadonlySet<T>andReadonlyMap<K, V>are structural types: a value matches when it has the members, with noimplementsclause. - The read-only types have no
push,addorset, so the checker stops code that takes them from changing them. - TypeScript has no shared size interface either, so
Sizedacceptssizeorlength.
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)))
}
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 ofintvalues, andslices.Values,maps.Keysandmaps.Valuesmake one from a built-in collection. - A
Seqhas no size, andlenworks only on built-in types, sodescribetakes the size as a second argument.
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()));
}
list: size 3, total 6
set: size 2, total 9
map values: size 2, total 7 (direct total 7)
- Verdict: stdlib. Rust has no
Collectiontrait.IntoIteratorlets a type be used in aforloop,ExactSizeIteratorgives the length, andFromIteratorletscollectbuild a collection. describeworks with a reference to any collection whose iterator knows its length, such asVecandBTreeSet. The compiler makes one copy of it for each type.
# 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)"
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.
Variations and related ideas
- 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
Iterablematch 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 itsaddthrows 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
ListorArrayListrefuses a set or a queue, even when the function only loops over its argument. Ask forIterableorCollection, or for the read-only form. - A map is not a collection. In Java, "the hierarchy consists of two distinct trees"1, and a
Mapdoes not extendCollection. In Kotlin, "Map doesn't extend Collection"7. PasskeySet(),values()orentrySet()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
Iterabletest, but a second loop over it finds nothing. A function that loops twice must ask for aCollection, 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
- Interfaces, The Java Tutorials (Collections), Whole page
- Interface Collection, Java SE 21, Interface description
- collections.abc, Python 3.14 documentation, Introduction; Collections Abstract Base Classes
- IEnumerable<T> Interface, .NET API reference, Definition
- ICollection<T> Interface, .NET API reference, Remarks
- IReadOnlyCollection<T> Interface, .NET API reference, Definition
- Collections overview, Kotlin documentation, Read-only and mutable collections
- Module std::iter, Rust standard library, for loops and IntoIterator
- Trait FromIterator, Rust standard library, Introduction
- Package iter, Go standard library, Overview; type Seq
- Iterators and Generators, The TypeScript Handbook, Iterables
- C++ named requirements, Container, cppreference.com, Introduction
- The Collection Interface, The Java Tutorials, Whole page
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag B506TN Edit this page History Report an error Markdown