Sample Java generic code

Default featured post

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 Test {
    public static void main(String args[]) {
        Test test = new Test();
        Vector v1 = new Vector();
        Vector v2 = new Vector();
        System.out.println(test.sum(v1, v2));

    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!";