Task 5 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

9.1 Generic classes — more than one type parameter

Lesson

Two placeholders at once

A class may declare several type parameters, separated by commas: class Pair<K, V>. Each is filled in independently, so a Pair<String, Integer> holds a String key and an Integer value. The names are conventional — T for type, E for element, K and V for key and value — but any identifier works.


Worked example

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

Pair<String, Integer> p = new Pair<String, Integer>("age", 30);
System.out.println(p.getKey());     // age
System.out.println(p.getValue());   // 30

Two independent placeholders, two different actual types.


▶ Try it: run this — a Pair with a String key and an Integer value; toString() prints them joined.



How do you declare two type parameters?


In Pair<String, Integer>, getValue() returns...


Type exactly what this program prints.

class Pair<K, V> {
    private K k; private V v;
    public Pair(K k, V v){ this.k=k; this.v=v; }
    public K getKey(){ return k; }
    public V getValue(){ return v; }
}
public class Main { public static void main(String[] a){
    Pair<String, Integer> p = new Pair<String, Integer>("x", 7);
    System.out.println(p.getKey());
    System.out.println(p.getValue());
}}

Match each conventional type-parameter name to its usual meaning.


True or false?