Friday, January 17, 2020

Introduction to Generics

What is Generic programming?

Generics were introduced into Java in JDK 5.0.  Generics incorporate stability to your code by making bugs detectable at compile time. Generic is a class or interface that deals in parametrized type. Generics enable developers to write more general and reusable Classes, Interfaces and methods. The essence of Generics is type safety. Programs can get infected by various bugs which will surface only at run time, without type safety. 

Benefits of Generic programming

  • Strong type checking at compile time
  • Removing type casting
  • Enabling programmers to write safe, general, reusable and more readable code
  • Generics add stability to code by making bugs detectable at compile time
Example:

import java.util.LinkedList;
public class GenricsTest {
      public static void main(String[] args) {
            LinkedList list=new LinkedList();
            list.add(12);//Without Genrics
            int i=(int)list.get(0);//Type casting required
           
            LinkedList<Integer> list1=new LinkedList();
            list1.add(12);//With generics
            int i1=list1.get(0);//No need of type casting
      }

}


Example: Writing a general Type



class Rectangle<T>{// General Rectangle type
      T h;
      T w;
      public Rectangle(T h, T w) {
            super();
            this.h = h;
            this.w = w;
      }
}
class Util{
      public static <T> void displayRectangle(Rectangle r)//generic method
      {
            System.out.println("h="+r.h+" w="+ r.w);
      }
}
public class GenericsDemo {
      public static void main(String[] args) {
      Rectangle<Integer> rint=new Rectangle<Integer>(12,20);//object-1
      Rectangle<Float> rfloat=new Rectangle<Float>(30.6f,23.5f);//object-2
      Util.<Integer>displayRectangle(rint);
      Util.<Float>displayRectangle(rfloat);
      }
}
Output:
h=12 w=20
h=30.6 w=23.5


Video Tutorial