Click here to watch in Youtube :
https://www.youtube.com/watch?v=vvOGucaFwuo&list=UUhwKlOVR041tngjerWxVccw
OrderedPair.java
https://www.youtube.com/watch?v=vvOGucaFwuo&list=UUhwKlOVR041tngjerWxVccw
OrderedPair.java
/**
* Multiple Type Parameters
*/
interface Pair<K, V>
{
public K getKey();
public V getValue();
}
/**
* As mentioned previously, a generic class can have multiple type parameters.
* For example, the generic OrderedPair class, which implements the generic Pair
* interface
*/
public 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;
}
}
GenericDemo.javaimport java.util.ArrayList;
import java.util.List;
public class GenericDemo
{
public static void main(String[] args)
{
Pair<String, Integer> pair1 = new OrderedPair<String, Integer>("age", 12);
System.out.println(pair1.getKey() + "=" + pair1.getValue());
Pair<String, String> pair2 = new OrderedPair<String, String>("user", "root");
System.out.println(pair2.getKey() + "=" + pair2.getValue());
List<String> nameList = new ArrayList<>();
nameList.add("Peter");
nameList.add("Ram");
/*
* We can also substitute a type parameter (i.e., K or V) with
* a parameterized type (i.e., List<String>).
*/
Pair<String, List<String>> pair3 = new OrderedPair<String, List<String>>(
"names", nameList);
System.out.println(pair3.getKey() + "=" + pair3.getValue());
}
}
Outputage=12
user=root
names=[Peter, Ram]
Click the below link to download the code:
No comments:
Post a Comment