Command Palette

Search for a command to run...

Back to the lesson: Topic 8.2 — Generic Classes and Interfaces
Core Java · Example 3 of 4 Java 16+

A generic record and nested type arguments

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.

01

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.

02

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.

03

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

01

How do you declare and use a generic class? Where can the type parameter appear inside it?

02

What are the two ways to implement a generic interface? Give an example of each.

03

Why can't a static field or static method use the class's type parameter?

04

Why is Box<Integer> not a subtype of Box<Number>? Compare with arrays.

A generic record and nested type arguments Java 16+
Sign in to run this example in your browser.

Expected output

Pair[key=Asha, value=92], key length 4
Pair[key=Asha, value=A+]
Ravi best: 81
{evening=Pair[key=17, value=21], morning=Pair[key=6, value=12]}
equal pairs: true