Generics in Java

 Generics- "An easy way to manage Objects"

In Generics, we will cover following topics:- 

  • What is generics?  
  • Generics Methods
  • Generics Classes 
  • Advantages of generics


Q.- What is generics?
The Java Generics programming is introduced in Java Standard Edition 5 to deal with type-safe objects.
The idea is to allow type (Integer, Float, Double, String, enum … etc and user defined types) to be a parameter to methods, classes and interfaces.

Here, question arises is that-  " why we learn generics? " 

we can understand this question with one problem.
problem is that, If we want to print name of 5 fruits with the help of function?
How can we solve this problem? 

Solution:-
class Test
{
  public static void main(String [ ] args)
  {
               String [] fruits=new String[] { "Apple", "Mango", "Banana" , "Grapes" , "Papaya"};
               Test.printFruits(fruits);
  }
  public static void printFruits(String [ ] f )  
  {
                for(String fr : f)
                {
                         System.out.print(fr+" ");
                }
  }  
} 

and again, If we want to print name of 5 fruits and marks of 5 subjects of  a student with the help of functions?
How can we solve this problem? 

Solution:-
class Test
{
  public static void main(String [ ] args)
  {
               String [ ] fruits=new String[] { "Apple", "Mango", "Banana" , "Grapes" , "Papaya"};
               Integer [ ] marks=new Integer[ ] { 99 , 87 , 69 , 96 , 89 };
               Test.printFruits(fruits);
               System.out.println();
           Test.printMarks(marks);
  }
  public static void printFruits(String [ ] f)  
  {
                for(String fr : f)
                {
                         System.out.print(fr+" ");
                }
   }  
  public static void printMarks(Integer [ ] n)  
   {
          for(Integer no : n)
          {
                  System.out.print(no+" ");
          }
  }
} 

In the above code, we have created 2 functions to solve a problem.

Can we solve this problem by using only one function?

Yes, we can solve this problem by using the concept called "Generics Method".

Generics Method:-

Generics method can be called with different types of arguments based on the type of arguments passed to generic method, the compiler handles each method based on argument type.
It can be static as well as non-static methods.
There are following  rules to create Generic Methods −
1. Generic method declarations have a type parameter delimited by diamond operator. (<T>)
2. Type parameter acts as placeholders for the types of the  arguments passed to the generic method.
3. A generic method's body is declared same as that of any other method. 
Note:-Type parameters can represent only reference types, not primitive types (like int, double and char).

Example:- 
public class Test {
  public static void main(String [] args)
  {
        String [ ] fruits=new String[] {"Apple", "Mango", "Banana", "Grapes" , "Papaya"};
        Integer [ ] marks=new Integer[ ] { 99 , 87 , 69 , 96 , 89 };
        Test.printArray(fruits);
        System.out.println();
        Test.printArray(marks);
   }
  public  static <G> void printArray(G [ ] s)
  {
         for(G x : s)
         {
               System.out.println(x);
         }
   }
}

Here, G is a type parameter that  can refer to any type (like String, Integer, and Employee)

Output:-

Apple Mango Banana Grapes Papaya 
99 87 69 96 89 


Type parameters:-

The common type parameters are as follows:-
T – Type
E – Element
K – Key
N – Number
V - Value

Generics Class:-

We can also define own classes with generics type. we use <> to specify parameter types in generic class creation.
To create an instance or object of generic class:-
Syntax:-
     <class_name> <T> obj = new <class_name> <T>();
Here, T type indicates that it can refer to any type (like String, Integer, and Employee). The type T to specify for the class will be used to store and retrieve the data.

Example:-
public class Example <G>
{
    G i;
    public void set(G a)
    {
      this.i=a;
    }
    public G get()
    {
      return i;
    }
    public static void main(String args[])
    {
      Example<Integer> obj=new Example<Integer>();
      Example<String> obj1=new Example<String>();
      obj.set(20);
      obj1.set("Naman");
      System.out.println(obj.get());
      System.out.println(obj1.get());
    }
} 

Output:-

20
Naman

Note:- We can also pass multiple Type parameters in a generics classes.
Example:-
class Test   <T , U>
{
    T  obj1;  // An object of type T
    U obj2;  // An object of type U
    // constructor
    Test(T obj1, U obj2)
    {
        this.obj1 = obj1;
        this.obj2 = obj2;
   } 
    // To print objects of T and U
    public void print()
    {
        System.out.println(obj1);
        System.out.println(obj2);
    }
class Main
{
    public static void main (String[] args)
    {
        Test <String, Integer> obj =  new Test<String, Integer>("Virat Kohli", 100);
        obj.print();
    }

}

Output:-

Virat Kohli
100 


Advantages of generics:-

There are mainly 3 advantages of generics they are as follows:-

1. Compile-time checking:- It is checked at compile time so problem will not occur at run-time.
Example:-

2. Code reuse:- We can write a method/class once and use for any type when we want.
3. Type-safety:- We can hold only a single type of objects in generics. It doesn’t allow to store other objects.
Without Generics, we can store any type of objects.

also see:-
Lambda expressions in java
Method references in java
Functional interface in java

Post a Comment

0 Comments