-
Notifications
You must be signed in to change notification settings - Fork 17
Java Generics Multiple Type Parameters Example
Ramesh Fadatare edited this page Aug 19, 2018
·
2 revisions
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.
Let's create a 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
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> {
...
}