Course contentsShow
← Java
Lesson 860 of 2,87021. Generics FundamentalsFree lesson

Multiple Type Parameters in a Single Class

Define classes with two or more type parameters like Pair<K, V>.

Multiple Type Parameters in a Single Class

What you'll learn: How to define generic classes with two or more type parameters to handle multiple types simultaneously.


The Core Idea

So far, you've worked with generic classes that have a single type parameter like Box<T>. But what if you need to store two different types together? Java lets you define classes with multiple type parameters separated by commas.

The most common example is a Pair class that holds two related values of potentially different types—like a dictionary entry with a key and a value.


Syntax and Usage

When declaring a generic class with multiple type parameters, list them all within the angle brackets:

public class Pair<K, V> {
    private K key;
    private V value;
    
    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }
    
    public K getKey() {
        return key;
    }
    
    public V getValue() {
        return value;
    }
}

Now you can instantiate Pair with two different types:

Pair<String, Integer> ageRecord = new Pair<>("Alice", 30);
String name = ageRecord.getKey();    // "Alice"
Integer age = ageRecord.getValue();  // 30

Pair<Integer, String> reverseMap = new Pair<>(404, "Not Found");

You can even use the diamond operator for cleaner instantiation:

Pair<String, Double> priceTag = new Pair<>("Coffee", 4.99);

Why This Matters

Multiple type parameters let you create flexible, reusable classes that maintain type safety across different types. Instead of creating separate classes for every combination, one generic class handles them all.

Key Takeaway: Define classes with multiple type parameters like Pair<K, V> by listing them comma-separated in angle brackets, enabling type-safe storage of multiple different types in a single class.