Sample Java generic code

Few days ago I was discussing with a friend of mine regarding some OOP concepts such as overriding, overloading, polymorphism and finally the discussion leaded to Generics in Java. Tonight, I have gotten little bit time to practice Generics. Basically, Generic is a type, for better understanding like Object type that you can assign anything Object to it. Anyway, Generics is very similar to C++ Template. Here I do not want to talk about the theory or concept of Generics. I have just added one example code of using Generics for those who have no idea about it and want to know about Generics.

import java.util.*;
public  class lily
{
public static void main(String args[])
{
     lily l = new lily();
     Vector v1 = new Vector();
     Vector v2 = new Vector();
     System.out.println(l.sum(v1,v2));
}
@SuppressWarnings("unchecked")
private <T> T sum(T x, T y)
{
     if(x.getClass() == Integer.class)
     {
         return (T) (Integer) ((Integer) x + (Integer) y);
     }
     else if(x.getClass() == String.class)
     {
         return (T) (String) ((String) x + (String) y);
     }
     else
     {
         return (T) "Hey wrong input type!";
     }
}
}

Send your idea and information to kasra@madadipouya.com

Leave a Reply