Lesson 117 min read
Collections & Generics
The right container for every job
Beyond Arrays and Lists
You already know List<T>, but C# has a whole toolbox of collections, each designed for a specific job. Picking the right one is like choosing the right container in your kitchen:
Dictionary<K,V>— a labeled filing cabinet powered by hash functions. Look things up instantly by key.HashSet<T>— a bag of unique items. No duplicates allowed. Fast checks for "is this in here?"Queue<T>— a line at a store. First in, first out (FIFO).Stack<T>— a stack of plates. Last in, first out (LIFO).
The <T> part is called a generic type parameter. It means "you decide what type goes in here." Generics give you type safety without writing separate code for each type.
Dictionary<K,V> — Key-Value Lookup
HashSet<T> — Unique Items Only
Queue & Stack — Order Matters
Queue<T> and Stack<T> control the order things come out:
- Queue (FIFO): Like a line at the movies. First person in line is first to get served. Use
Enqueue()to add,Dequeue()to remove. - Stack (LIFO): Like a stack of pancakes. The last pancake added is the first one eaten. Use
Push()to add,Pop()to remove.
Both have a Peek() method that lets you look at the next item without removing it.
Queue<T> and Stack<T>
Writing Your Own Generic Code
You can create your own generic classes and methods. The <T> is a placeholder that gets replaced with a real type when someone uses your code. It's like a recipe that says "take one item of type T" — the cook decides what T is.
Generic Methods & Classes
Note: 🗂️ Collection cheat sheet: Need to look up by key? → Dictionary. Need uniqueness? → HashSet. Need FIFO order? → Queue. Need LIFO/undo? → Stack. Need a flexible ordered list? → List. Choosing the right collection is half the battle!
Quick check
Continue reading
Hash FunctionsData Structure
Collisions, load factor, probingSets vs MapsData Structure
Use cases and tradeoffsDynamic ArraysData Structure
Resizing strategy, amortized O(1) pushCollections FrameworkJava
List, Set, Map — the power tools of JavaDictionaries & SetsPython
Look things up by name instead of by number