Thursday, 8 June 2017

Java Tutorial: Generics in java | Java Generics [Generic method - order pair] ~ foundjava


Click here to watch in Youtube :
https://www.youtube.com/watch?v=RfjljjY03Ho&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial: Generics in java | Java Generics [Generic method - order pair]
OrderPair.java
public class OrderPair<K, V>
{

    private K key;
    private V value;

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

    public void setKey(K key)
    {
        this.key = key;
    }

    public void setValue(V value)
    {
        this.value = value;
    }

    public K getKey()
    {
        return key;
    }

    public V getValue()
    {
        return value;
    }
}
GenericDemo.java
public class GenericDemo
{

    public static void main(String[] args)
    {
        OrderPair<Integer, String> p1 = new OrderPair<Integer, String>(1, "apple");
        OrderPair<Integer, String> p2 = new OrderPair<Integer, String>(1, "apple");
        boolean same = GenericDemo.compare(p1, p2);
        
        //Like below also we can invoke. 
        //boolean same = GenericDemo.<Integer, String>compare(p1, p2);
        System.out.println("is p1 and p2 are same? = " + same);

    }

    public static <K, V> boolean compare(OrderPair<K, V> p1,
                                                    OrderPair<K, V> p2)
    {
        return p1.getKey().equals(p2.getKey())
                && p1.getValue().equals(p2.getValue());
    }

}
Output
is p1 and p2 are same? = true
Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment