A generic stack used with two element types
A generic class declares one or more type parameters, like class Box<T>, and uses them as types for its fields, parameters and return values. Each user picks the real type (Box<String>, Box<Integer>), and the compiler checks every use against it.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a generic class Counter<T> that counts how many times each item is added (use a TreeMap<T, Integer> inside) and prints the counts for the strings b, a, b, c, b.
Write a generic interface interface Source<T> { T next(); } and a class CountingSource implements Source<Integer> that returns 1, 2, 3... Print the first three values.
Write a generic class Cache<K, V> with put, get and size, backed by a HashMap<K, V>. Store two Integer-to-String entries and print a hit, a miss (null) and the size.
Explain it without notes
How do you declare and use a generic class? Where can the type parameter appear inside it?
What are the two ways to implement a generic interface? Give an example of each.
Why can't a static field or static method use the class's type parameter?
Why is Box<Integer> not a subtype of Box<Number>? Compare with arrays.
Expected output
Stack[home, search, product]
back from: product
now on: search
sum: 60
error: stack is empty