Sub topic 5
Classes with Multiple Type Parameters
So far you have seen a generic class with one type parameter, like Box<T>. A type parameter is a placeholder name for a type. The person using the class fills it in later. Often, though, one placeholder is not enough. A phone book links a name to a number. A score table links a player to points. These ideas need two types at once.
This chapter shows how to give one class two or more type parameters, how to use them, and the mistakes beginners make most often.
Why One Type Parameter Is Not Enough
Suppose you want a class that holds a person's name and their age. With one type parameter, you would have to pick one type for both values:
Box<String>can hold the name, but the age would have to be text, like"36".Box<Integer>can hold the age, but not the name.Box<Object>can hold either, but then you are back to casting, the problem generics were meant to fix.
What you really want is a class where the first value has one type and the second value has a different type. The compiler should check both of them.
Declaring Two Type Parameters
You list several type parameters inside the angle brackets, separated by commas. Here is a Pair class with a key (the first value) and a value (the second value):
public class Pair<K, V> {
private final K key;
private final V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}Read Pair<K, V> as "a Pair of some type K and some type V." Inside the class:
Kis used wherever the key appears: the field, the constructor argument, and the getter.Vis used wherever the value appears.KandVare independent. They can be different types, or they can be the same type.
The names K and V follow the naming conventions from the earlier chapter: K for key, V for value.
Using the Class
When you create a Pair, you give one real type for each type parameter, in the same order as the declaration. Save the class above as Pair.java, then put this in PairDemo.java in the same folder:
public class PairDemo {
public static void main(String[] args) {
Pair<String, Integer> age = new Pair<>("Ada", 36);
String name = age.getKey(); // K is String
Integer years = age.getValue(); // V is Integer
System.out.println(name + " is " + years);
}
}Compile and run it:
javac Pair.java PairDemo.java
java PairDemoThe output is:
Ada is 36Notice that getKey() returns a String and getValue() returns an Integer. You did not write a single cast. The diamond <> on the right side works here just as it did with one parameter. The compiler copies both types, String and Integer, from the left side.
The Compiler Checks Each Parameter
Each type parameter gets its own check. If you mix them up, the code does not compile:
public class PairErrors {
public static void main(String[] args) {
Pair<String, Integer> p = new Pair<>("Ada", 36);
// Integer wrong = p.getKey(); // compile error: getKey() returns String
// Pair<String, Integer> q = new Pair<>(36, "Ada"); // compile error: arguments in wrong order
String ok = p.getKey();
System.out.println(ok);
}
}Both commented lines are mistakes the compiler catches for you. Without generics, they would only fail when the program ran.
Same Type Twice Is Fine
Nothing says K and V must be different. A pair of first and last names uses String for both:
public class SameTypeDemo {
public static void main(String[] args) {
Pair<String, String> fullName = new Pair<>("Grace", "Hopper");
System.out.println(fullName.getKey() + " " + fullName.getValue());
}
}This prints Grace Hopper. The two parameters are separate slots. Filling both slots with the same type is allowed.
Type Arguments Can Be Generic Too
A type argument is the real type you put in a slot, like String or Integer. A type argument can itself be a generic type. That lets you build richer shapes from simple pieces:
import java.util.List;
public class NestedDemo {
public static void main(String[] args) {
Pair<String, List<Integer>> scores =
new Pair<>("Linus", List.of(90, 85, 77));
int total = 0;
for (int s : scores.getValue()) {
total += s;
}
System.out.println(scores.getKey() + " scored " + total);
}
}Here V is List<Integer>, so getValue() returns a List<Integer>. The program prints Linus scored 252. You can nest as deep as you like, for example Pair<String, Pair<Integer, Integer>>. Deep nesting gets hard to read quickly, though. If a type becomes long, consider writing a small named class instead.
More Than Two Parameters
You can declare as many type parameters as you need. A Triple holds three values:
public class Triple<A, B, C> {
private final A first;
private final B second;
private final C third;
public Triple(A first, B second, C third) {
this.first = first;
this.second = second;
this.third = third;
}
public A getFirst() { return first; }
public B getSecond() { return second; }
public C getThird() { return third; }
}
// Triple<String, Integer, Boolean> t = new Triple<>("Ada", 36, true);Java's own library rarely goes past two or three. Map<K, V> uses two. java.util.function.BiFunction<T, U, R> uses three: two input types and one result type.
Common Beginner Mistakes
| Mistake | Example | Fix |
|---|---|---|
| Wrong number of type arguments | `Pair<String> p` | Give one type for each parameter: `Pair<String, Integer>` |
| Arguments in the wrong order | `new Pair<>(36, "Ada")` for `Pair<String, Integer>` | Match the order of the declaration |
| Primitive type argument | `Pair<String, int>` | Use the wrapper class `Integer` |
| Reading the wrong getter | `Integer n = p.getKey()` | Check which parameter each method returns |
| Leaving out type arguments | `Pair p = new Pair("a", 1)` | This is a raw type. Always write the type arguments |
Summary
- A class can declare several type parameters, separated by commas:
class Pair<K, V>. - Each parameter is filled in on its own, in the order it was declared.
- The parameters can be the same type or different types.
- A type argument can be another generic type, such as
List<Integer>. - The diamond
<>infers all the type arguments at once.
Exercise
Write the declaration line for a variable entry of type Pair whose key is a String and whose value is a Double, and create it with the key "pi" and the value 3.14 using the diamond operator. What type does entry.getValue() return?
Show answer
Pair<String, Double> entry = new Pair<>("pi", 3.14); The method entry.getValue() returns Double, because V was filled in with Double.
Exercise
Given Pair<Integer, String> p = new Pair<>(7, "seven");, which of these lines compile? (1) String s = p.getKey(); (2) Integer n = p.getKey(); (3) String t = p.getValue();
Show answer
Lines 2 and 3 compile. Line 1 does not, because getKey() returns K, which is Integer here, and an Integer cannot be assigned to a String.
Exercise
Write a generic class Labeled<L, T> with a final field label of type L and a final field item of type T, a constructor taking both, and getters getLabel() and getItem(). Then show one line that creates a Labeled with label "count" and item 10.
Show answer
public class Labeled<L, T> { private final L label; private final T item; public Labeled(L label, T item) { this.label = label; this.item = item; } public L getLabel() { return label; } public T getItem() { return item; } } and the usage line: Labeled<String, Integer> c = new Labeled<>("count", 10);