Java Generics Multiple Type Parameters Example

A generic class can have multiple type parameters. In this article, we will learn how to create a generic class and interface with multiple type parameters examples.

Java Generics Multiple Type Parameters Example

Let's create an OrderedPair class which is a generic multiple type parameters class. The generic OrderedPair class, which implements the generic Pair interface:
public class GenericMultipleTypeParametersExample {
 public static void main(String[] args) {
  OrderedPair<String, Integer> p1 = new OrderedPair<>("Even", 8);
  System.out.println(p1.getKey());
  System.out.println(p1.getValue());
  
  OrderedPair<String, String>  p2 = new OrderedPair<>("hello", "world");
  System.out.println(p2.getKey());
  System.out.println(p2.getValue());
  
  OrderedPair<String, Employee>  p3 = new OrderedPair<>("key", new Employee("Ramesh"));
  System.out.println(p3.getKey());
  System.out.println(p3.getValue().getName());
 }
}

class Employee{
 private String name;
 Employee(String name){
  this.name = name;
 }
 
 public String getName(){
  return this.name;
 }
}

interface Pair<K, V> {
    public K getKey();
    public V getValue();
}

class OrderedPair<K, V> implements Pair<K, V> {

    private K key;
    private V value;

    public OrderedPair(K key, V value) {
 this.key = key;
 this.value = value;
    }

    public K getKey() { return key; }
    public V getValue() { return value; }
}
Output:
Even
8
hello
world
key
Ramesh

Real-world Example for Multiple Type Parameters

HashMap class is a good example of Multiple Type Parameters.
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
//...
}
The interface type Map interface is a good example for Multiple Type Parameters.
public interface Map<K, V> {
...
}

Related Java Generics Examples

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments