Generics: a Box for Any Type

How C#, Java and TypeScript write one class that works for any type of item, read aloud as "a list of snacks", and why Python and JavaScript don't need the label.

Apprentice · C# · Java · Python · JavaScript · TypeScript · Updated

By

After this lesson you can

  • Read a generic type such as List<Snack> and say what the type in angle brackets means
  • Write a small generic class that works for any type of item

Key takeaways

  • A generic class is written once with a placeholder type, usually T, and filled in when it's used, such as Shelf<string> or Shelf<int>.
  • List<Snack> reads aloud as "a list of snacks". The type in the angle brackets says what the structure holds.
  • C#, Java and TypeScript check the type, so a shelf of snacks can't take a number by mistake. Python and JavaScript don't need the label.
  • Java's generics hold objects, so a list of whole numbers is List<Integer>, not List<int>.

The snack stand has a shelf for snacks and a shelf for price tags. Both shelves work the same way: put something on, take something off, count what's there. It would be silly to build two kinds of shelf. In code, a generic class is that one shelf, built once and used for snacks, prices, songs or anything else. Every structure from Module 2 on is generic, so a list, a stack or a tree can hold whatever your program needs.

Reading the angle brackets

You've already used a generic class: List<string> in C#, List<String> in Java, string[] (another way of writing Array<string>) in TypeScript. The type in the angle brackets, < >, says what the structure holds. Read it aloud as "of":

You write You say
List<string> "a list of strings"
List<Snack> "a list of snacks"
Shelf<int> "a shelf of whole numbers"

C#, Java and TypeScript check that label. Put a number on a shelf of snacks, and the code won't run; the mistake is caught before anyone sees it.

Writing one: a shelf for anything

To write a generic class, give it a type parameter: a placeholder name in angle brackets, usually T for "type". Inside the class, T stands for whatever type the shelf is used with. Here's a small Shelf that holds items of any type:

Shelf<string> snackShelf = new Shelf<string>();
snackShelf.Add("Pretzel");
snackShelf.Add("Trail Mix");

Shelf<int> priceShelf = new Shelf<int>();
priceShelf.Add(3);
priceShelf.Add(4);

Console.WriteLine("Snack shelf: " + snackShelf.Count() + " items, first is " + snackShelf.Get(0));
Console.WriteLine("Price shelf: " + priceShelf.Count() + " items, total quot; + (priceShelf.Get(0) + priceShelf.Get(1)));

class Shelf<T>
{
    private List<T> items = new List<T>();

    public void Add(T item)
    {
        items.Add(item);
    }

    public T Get(int index)
    {
        return items[index];
    }

    public int Count()
    {
        return items.Count;
    }
}
Snack shelf: 2 items, first is Pretzel
Price shelf: 2 items, total $7
class Shelf<T> {
    private List<T> items = new ArrayList<>();

    void add(T item) {
        items.add(item);
    }

    T get(int index) {
        return items.get(index);
    }

    int count() {
        return items.size();
    }
}

void main() {
    Shelf<String> snackShelf = new Shelf<>();
    snackShelf.add("Pretzel");
    snackShelf.add("Trail Mix");

    Shelf<Integer> priceShelf = new Shelf<>();
    priceShelf.add(3);
    priceShelf.add(4);

    IO.println("Snack shelf: " + snackShelf.count() + " items, first is " + snackShelf.get(0));
    IO.println("Price shelf: " + priceShelf.count() + " items, total quot; + (priceShelf.get(0) + priceShelf.get(1)));
}
Snack shelf: 2 items, first is Pretzel
Price shelf: 2 items, total $7
class Shelf:
    def __init__(self):
        self.items = []

    def add(self, item):
        self.items.append(item)

    def get(self, index):
        return self.items[index]

    def count(self):
        return len(self.items)


snack_shelf = Shelf()
snack_shelf.add("Pretzel")
snack_shelf.add("Trail Mix")

price_shelf = Shelf()
price_shelf.add(3)
price_shelf.add(4)

print(f"Snack shelf: {snack_shelf.count()} items, first is {snack_shelf.get(0)}")
print(f"Price shelf: {price_shelf.count()} items, total ${price_shelf.get(0) + price_shelf.get(1)}")
Snack shelf: 2 items, first is Pretzel
Price shelf: 2 items, total $7
class Shelf {
  constructor() {
    this.items = [];
  }

  add(item) {
    this.items.push(item);
  }

  get(index) {
    return this.items[index];
  }

  count() {
    return this.items.length;
  }
}

const snackShelf = new Shelf();
snackShelf.add("Pretzel");
snackShelf.add("Trail Mix");

const priceShelf = new Shelf();
priceShelf.add(3);
priceShelf.add(4);

console.log(`Snack shelf: ${snackShelf.count()} items, first is ${snackShelf.get(0)}`);
console.log(`Price shelf: ${priceShelf.count()} items, total ${priceShelf.get(0) + priceShelf.get(1)}`);
Snack shelf: 2 items, first is Pretzel
Price shelf: 2 items, total $7
class Shelf<T> {
  private items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  get(index: number): T {
    return this.items[index];
  }

  count(): number {
    return this.items.length;
  }
}

const snackShelf = new Shelf<string>();
snackShelf.add("Pretzel");
snackShelf.add("Trail Mix");

const priceShelf = new Shelf<number>();
priceShelf.add(3);
priceShelf.add(4);

console.log(`Snack shelf: ${snackShelf.count()} items, first is ${snackShelf.get(0)}`);
console.log(`Price shelf: ${priceShelf.count()} items, total ${priceShelf.get(0) + priceShelf.get(1)}`);
Snack shelf: 2 items, first is Pretzel
Price shelf: 2 items, total $7

One blueprint card for a shelf of any type, T, with two arrows down to two shelves built from it: a shelf of strings, holding the words Pretzel and Trail Mix, and a shelf of whole numbers, holding 3 and 4

The total, $7, is real arithmetic: the price shelf hands back numbers, so adding them works. On a C#, Java or TypeScript snack shelf, the same + would join text instead, and the type label tells you which you'll get before you run anything.

Why Python and JavaScript don't need it

Python and JavaScript don't check types before the code runs, so any list or class already holds anything; their Shelf above has no T at all. That's simpler to write, and the trade-off is that a mistake, such as a number on a snack shelf, only shows up when the code runs. Newer Python can add the label as a hint for tools (class Shelf[T]:), and TypeScript exists largely to add these labels to JavaScript.

One Java detail: Integer, not int

Java's generics hold objects, and a plain int isn't one. So a shelf of whole numbers is Shelf<Integer>, and a list of them List<Integer>. Java turns 3 into an Integer and back for you, so the rest of the code looks the same. C# has no such rule: Shelf<int> is fine.

Try it. Make a third shelf that holds Snack objects from Classes and Objects: Shelf<Snack> in C#, Java and TypeScript. Add two snacks, and print the name of the first one.

Check yourself

2 questions to try on the lesson page.

So what

From Module 2 on, every structure you build is generic: Stack<T>, LinkedList<T>, HashTable<K, V>. When you see the angle brackets, read them as "of", and you'll always know what the structure holds.

Key terms

Cheat sheets