Sub topic 5
Classes with Multiple Type Parameters
A generic class does not have to stop at one type parameter. A type parameter is a placeholder name, such as T, that the caller replaces with a real type. Some classes need to hold two or more values of different types, so they need more than one placeholder.
Why One Type Parameter Is Not Enough
Picture a name paired with an age. The name is a String and the age is an Integer. A Box<T> holds only one type. You could use Box<Object>, but then you are back to casting, which is the problem generics were made to fix.
The fix is to declare two type parameters. You list them inside the angle brackets and separate them with commas.
Declaring a Pair Class
The class below uses K for "key" and V for "value". Each one is replaced on its own when you use the class.
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; }
}
public class PairDemo {
public static void main(String[] args) {
Pair<String, Integer> age = new Pair<>("Ada", 36);
String name = age.getKey(); // no cast needed
int years = age.getValue(); // Integer unboxes to int
System.out.println(name + " is " + years);
Pair<String, String> capital = new Pair<>("France", "Paris");
System.out.println(capital.getKey() + " -> " + capital.getValue());
}
}Save this as PairDemo.java, then run javac PairDemo.java and java PairDemo. It prints:
Ada is 36
France -> ParisHow the Types Are Filled In
The order matters. The first type argument replaces the first type parameter, the second replaces the second, and so on.
| Declaration | K becomes | V becomes |
|---|---|---|
| `Pair<String, Integer>` | `String` | `Integer` |
| `Pair<Integer, String>` | `Integer` | `String` |
| `Pair<String, String>` | `String` | `String` |
The last row shows that two parameters can be given the same type. Separate parameters only mean the types are allowed to differ. They do not have to.
Where You Have Seen This Before
The Java library uses multiple type parameters a lot. Map<K, V> maps keys of type K to values of type V. For example, Map<String, Integer> could map words to how many times each one appears. When you write Map<String, Integer>, the same position rule applies.
Exercise
Write a declaration that creates a Pair holding a Boolean as its key and a Double as its value, with key true and value 9.5. What type does getValue() return?
Show answer
Pair<Boolean, Double> p = new Pair<>(true, 9.5); The method getValue() returns Double, because V is replaced by Double.
Exercise
Will this line compile? Pair<String, Integer> p = new Pair<>(36, "Ada"); Explain why.
Show answer
No. K is String, so the first constructor argument must be a String, but 36 is an Integer. V is Integer, but "Ada" is a String. The arguments are in the wrong order.