Monday, 15 May 2017

Java Tutorial: Generics in java [Generic Interface and Class using multiple type parameters]


Click here to watch in Youtube : 
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.java
import 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());

    }

}
Output
age=12
user=root
names=[Peter, Ram]
Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/GenericsDemo_multi_type_param_App.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/GenericsDemo_multi_type_param_App

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/47d09ebb24294f7b507419345f38ec4cde27d544/BasicJava/GenericsDemo_multi_type_param_App/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment