Conceptintro
Generic containers
Also called generic collections, typed collections, container of T, List of T, Vec, HashMap, parameterized collection, raw type.
A generic container, such as List<T> or HashMap<K, V>, takes the types of its items as type parameters, so one container type works for every item type and the compiler checks each use.
- Applies to
- core-languages
Idea
A program keeps many kinds of things in lists, maps and sets: numbers, names, orders. The code of a list is the same for each kind of item, so a language should not need one list type for numbers and another for names. A generic container takes the type of its items as a parameter. list[int] is a list of integers and dict[str, int] is a map from strings to integers, but both use the code of list and dict.
from collections import deque
# The type arguments say what each container holds.
scores: list[int] = [90, 85]
ages: dict[str, int] = {"ann": 31}
waiting: deque[str] = deque(["a", "b"])
scores.append(77)
ages["bob"] = 25
waiting.append("c")
print(sum(scores), sorted(ages), waiting.popleft())
# Python does not check the items when the program runs.
scores.append("ninety") # a type checker reports this line
print(scores)
252 ['ann', 'bob'] a
[90, 85, 77, 'ninety']
The annotations make scores a list of int and ages a map from str to int. A type checker such as mypy uses them to reject the call that adds a string to scores. Python itself runs that line, because the list stores any object.
How it works
Containers. A container is a class or a data structure "whose instances are collections of other objects"1. "Containers may be classified as either single-value containers or associative containers"1: a list or a set stores single values, and a map stores pairs of a key and a value.
The item type is a parameter. Generics "enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods"2. A container declares a type parameter for its items, such as T in List<T>, and the code that uses it supplies a type argument, such as List<String>. The Python glossary defines a generic type as "A type that can be parameterized; typically a container class such as list or dict"3. A map has two parameters, one for the keys and one for the values. See type constructor.
The compiler checks the items. Without generics, a container holds the most general type, such as Object, and the code must cast each item that it reads. The Java tutorial lists the benefits of generics: "Stronger type checks at compile time" and "Elimination of casts"2. A List<String> accepts only strings, and get returns a String.
The usual containers. Most languages have a growable array, a hash map and a set in the standard library. In .NET, "List is a generic version of ArrayList"4 and Dictionary<TKey,TValue> "is a generic version of Hashtable"4. Rust has Vec<T>, "A contiguous growable array type"5, and HashMap<K, V>. In C++, "std::vector is a sequence container that encapsulates dynamic size arrays"6. In TypeScript, an array type is written number[], and "You may also see this written as Array, which means the same thing"7.
Constraints on the items. Some containers need more from the item type. A hash map must hash and compare its keys. In Rust, "It is required that the keys implement the Eq and Hash traits"8. A sorted container needs an order on its keys.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Absent | An Array, a Map or a Set holds values of any type, and the language has no way to give a container an item type. |
| TypeScript | Native | |
| Go | Native | |
| Rust | Standard library | |
| Kotlin | Standard library | The Kotlin standard library has generic collections, such as List<T>, MutableList<T>, Map<K, V> and Set<T>. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A table is not a value with an item type. |
| Bash | Does not apply | Bash arrays hold strings only, so they have no item types. |
| PowerShell | Standard library | PowerShell can use the generic collections of .NET, such as a List of int. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no containers of typed values. |
| CSS | Does not apply | CSS has no containers of typed values. |
| Regular expressions | Does not apply | A regular expression has no containers. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | list, dict, set, tuple and collections types, with type arguments for static checkers |
| JavaScript | absent | Array, Map and Set hold values of any type; the language has no item types |
| TypeScript | native | T[] and Array<T>, Map<K, V>, Set<T> |
| Java | stdlib | List<E>, Map<K, V>, Set<E> in java.util; items must be objects |
| Kotlin | stdlib | List<T> and MutableList<T>, Map<K, V>, Set<T> |
| C# | stdlib | List<T>, Dictionary<TKey,TValue>, HashSet<T> in System.Collections.Generic |
| Go | native | built-in slice and map types such as []T and map[K]V; generic types for others |
| Rust | stdlib | Vec<T>, HashMap<K, V>, HashSet<T>, VecDeque<T> |
| C | idiom | void * items with the size of an item, or a macro that makes a struct for each type |
| C++ | stdlib | std::vector<T>, std::unordered_map<K, V>, std::set<T> |
| Bash | n/a | arrays hold strings only |
| PowerShell | stdlib | .NET generic collections, such as [System.Collections.Generic.List[int]] |
| SQL | n/a | a table is not a value with an item type |
| Regex | n/a | a pattern has no containers |
| HTML | n/a | HTML has no containers of typed values |
| CSS | n/a | CSS has no containers of typed values |
Java, C#, Rust and C++ have their generic containers in the standard library. Go has slices and maps in the language, and its older packages, such as container/list, store items of type any. Python and TypeScript have item types only for the checker. JavaScript containers hold any value, so the program must check the items itself.
The example files show these differences. Python shows list, dict and defaultdict with type arguments. TypeScript shows Array<T> and Map<K, V>. Java shows a List<String>, a raw List and the boxing of int. C# shows List<int> and Dictionary<string, List<int>>. Go shows a slice, a map and container/list with a type assertion. Rust shows Vec<T>, HashMap<K, V> and a key type that derives Hash. C shows a list of void * items. C++ shows std::vector and std::unordered_map.
from collections import defaultdict
def group_by_length(words: list[str]) -> dict[int, list[str]]:
groups: defaultdict[int, list[str]] = defaultdict(list)
for w in words:
groups[len(w)].append(w)
return dict(groups)
print(group_by_length(["ox", "cat", "dog", "emu", "be"]))
print(list[int], dict[str, int])
{2: ['ox', 'be'], 3: ['cat', 'dog', 'emu']}
list[int] dict[str, int]
- Verdict: native.
list,dictanddefaultdicttake type arguments in square brackets.list[int]is a generic alias type, and a type checker uses it to check the items. Python does not check the items when the program runs.
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
int main() {
std::vector<int> v{3, 1, 2};
v.push_back(4);
int sum = 0;
for (int x : v) {
sum += x;
}
std::cout << v.size() << " " << sum << "\n";
std::unordered_map<std::string, std::vector<int>> m;
m["a"].push_back(1);
m["a"].push_back(2);
std::cout << m["a"].size() << " " << m.count("b") << "\n";
}
4 10
2 0
- Verdict: stdlib.
std::vector<T>andstd::unordered_map<K, V>are class templates. The compiler makes a version for each type argument, so astd::vector<int>holds theintvalues themselves.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
@SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("ann");
String first = names.get(0); // no cast
System.out.println(first.toUpperCase());
// List<int> is an error, so the list holds Integer objects.
List<Integer> nums = new ArrayList<>();
nums.add(8); // the compiler boxes 8
Map<String, List<Integer>> m = new HashMap<>();
m.put("a", nums);
System.out.println(m);
// A raw List accepts any object.
List raw = names;
raw.add(42);
try {
String s = names.get(1);
System.out.println(s);
} catch (ClassCastException e) {
System.out.println("ClassCastException");
}
}
}
ANN
{a=[8]}
ClassCastException
- Verdict: stdlib.
List<E>andMap<K, V>are generic interfaces injava.util. A type argument must be a reference type, so a list of numbers is aList<Integer>. The rawListlets the program add anIntegerto a list of strings, and the error comes when the program reads it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A list of items of any one size: the code does not know the type. */
struct list {
void *data;
size_t size, len, cap;
};
static void push(struct list *l, const void *item) {
if (l->len == l->cap) {
l->cap = l->cap ? l->cap * 2 : 4;
l->data = realloc(l->data, l->cap * l->size);
}
memcpy((char *)l->data + l->len * l->size, item, l->size);
l->len++;
}
int main(void) {
struct list ints = {NULL, sizeof(int), 0, 0};
for (int i = 1; i <= 5; i++) {
push(&ints, &i);
}
int *p = ints.data; /* the caller knows the type */
printf("%zu %d %d\n", ints.len, p[0], p[4]);
struct list doubles = {NULL, sizeof(double), 0, 0};
double d = 2.5;
push(&doubles, &d);
printf("%.1f\n", ((double *)doubles.data)[0]);
free(ints.data);
free(doubles.data);
return 0;
}
5 1 5
2.5
- Verdict: idiom. C has no generic types. The list stores bytes through a
void *and the size of an item, and the caller converts the pointer to the item type. The compiler cannot check that the caller uses the right type.
using System;
using System.Collections.Generic;
var nums = new List<int> { 3, 1, 2 };
nums.Sort();
var groups = new Dictionary<string, List<int>>();
groups["odd"] = nums.FindAll(n => n % 2 == 1);
groups["even"] = nums.FindAll(n => n % 2 == 0);
foreach (var (key, list) in groups)
{
Console.WriteLine($"{key}: {string.Join(",", list)}");
}
var seen = new HashSet<string> { "a", "b", "a" };
Console.WriteLine(seen.Count);
odd: 1,3
even: 2
2
- Verdict: stdlib.
List<T>,Dictionary<TKey,TValue>andHashSet<T>are inSystem.Collections.Generic. AList<int>holds theintvalues themselves, with no boxing.
const scores: Array<number> = [90, 85];
const same: number[] = scores;
const byName = new Map<string, number[]>();
byName.set("ann", same);
byName.get("ann")?.push(77);
for (const [name, list] of byName) {
console.log(name, list.length, list.reduce((a, b) => a + b, 0));
}
console.log(new Set<string>(["a", "b", "a"]).size);
ann 3 252
2
- Verdict: native.
Array<number>andnumber[]are the same type.Map<string, number[]>andSet<string>take type arguments. The checker removes the types before the program runs.
package main
import (
"container/list"
"fmt"
)
// Stack is a generic type: Stack[int] holds only ints.
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }
func main() {
scores := []int{90, 85}
ages := map[string]int{"ann": 31}
var s Stack[string]
s.Push("a")
fmt.Println(len(scores), ages["ann"], s.items)
// container/list stores items of type any.
l := list.New()
l.PushBack(1)
l.PushBack("two")
for e := l.Front(); e != nil; e = e.Next() {
if n, ok := e.Value.(int); ok {
fmt.Println("int", n)
} else {
fmt.Println("other", e.Value)
}
}
}
2 31 [a]
int 1
other two
- Verdict: native. Slices and maps, such as
[]intandmap[string]int, are built-in generic containers, and a program can declare its own generic types.container/listis older: its items have the typeany, so the code uses a type assertion to read them.
use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
enum Color {
Red,
Blue,
}
fn main() {
let mut v: Vec<i32> = Vec::new();
v.push(3);
v.extend([1, 2]);
v.sort();
println!("{:?}", v);
// The key type must implement Eq and Hash.
let mut counts: HashMap<Color, usize> = HashMap::new();
for c in [Color::Red, Color::Blue, Color::Red] {
*counts.entry(c).or_insert(0) += 1;
}
println!("{} {}", counts[&Color::Red], counts[&Color::Blue]);
}
[1, 2, 3]
2 1
- Verdict: stdlib.
Vec<T>andHashMap<K, V>are in the standard library.ColorderivesEqandHash, so it can be a key of aHashMap.
Variations and related ideas
- Erased or specialized. Java keeps one copy of the container code, and the items are objects. "You can substitute only non-primitive types for the type parameters"9, so a
List<Integer>holds boxed integers. .NET, Rust and C++ make a version of the container for each item type, so aList<int>holds the integers themselves. See type erasure. - Containers of any type. Before generics, a container held the most general type. Go has
container/list, whosePushBacktakesv any, and eachElementhas a fieldValue any10. The code must check the type of each item that it reads. - Read-only views. Many libraries have a read-only interface for a container, such as
IReadOnlyList<T>in .NET orList<T>in Kotlin, so that a function can take a list without the right to change it.
Pitfalls
- Raw types in Java. "A raw type is the name of a generic class or interface without any type arguments"11. "Raw types show up in legacy code because lots of API classes (such as the Collections classes) were not generic prior to JDK 5.0"11. A raw
Listaccepts any object, and the error comes when the program reads an item. Write the type argument. - No primitive types in Java.
List<int>is a compile error. UseList<Integer>. The compiler boxes eachint, as it "autoboxes 8 to Integer.valueOf(8)"9. - Item types that are not checked. In Python and TypeScript, the type arguments are checked only by the type checker. "The Python runtime does not enforce type annotations"12, so a
list[int]can hold a string. Data that comes from a file or the network must be checked when it is read. - A list of a subtype is not a list of the supertype. In Java, "MyClass has no relationship to MyClass, regardless of whether or not A and B are related"13. A method that takes a
List<Number>does not take aList<Integer>, because it could add aDoubleto it. See subtyping.
Cost
A generic container costs nothing extra in the code that the compiler checks. The cost comes from how the language stores the items. In Java, the items are objects, so a list of numbers holds a reference to each boxed number. .NET avoids this: "Generic collection types generally perform better for storing and manipulating value types because there is no need to box the value types"14. In C++, the elements of a std::vector "are stored contiguously"6, and a Vec<T> in Rust is contiguous too5.
History
"Generic programming was introduced to the mainstream with Ada in 1977. With templates in C++, generic programming became part of the repertoire of professional library design."15 Java collections took type parameters in JDK 5.0, and older code still has raw types from before that change11. .NET has generic versions of its older collections, so List<T> replaced ArrayList4.
References
- Container (abstract data type), Wikipedia, Introduction; Types
- Why Use Generics?, The Java Tutorials, Whole page
- Glossary, Python 3.14 documentation, generic type
- Generic collections in .NET, .NET documentation, System.Collections.Generic
- Struct Vec, Rust standard library, Introduction
- std::vector, C++ reference, cppreference.com, Introduction
- Everyday Types, The TypeScript Handbook, Arrays
- Struct HashMap, Rust standard library, Introduction
- Restrictions on Generics, The Java Tutorials, Cannot Instantiate Generic Types with Primitive Types
- Package list, Go standard library, Overview; type Element; func (*List) PushBack
- Raw Types, The Java Tutorials, Whole page
- Built-in Types, Python 3.14 documentation, Generic Alias Type
- Generics, Inheritance, and Subtypes, The Java Tutorials, Whole page
- Generics in .NET, .NET documentation, Advantages and disadvantages of generics
- Generic programming, Wikipedia, Introduction
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 EX6J3D Edit this page History Report an error Markdown