What is need of introducing Generics, when Arrays already present in Java?


Arrays in Java are used to store homogeneous datatypes, where generics allow users to dynamically choose the type (class) that a method, constructor of a class accepts, dynamically.

By defining a class generic you are making it type-safe i.e. it can act up on any datatype. To understand generics let us consider an example −

Example

 Live Demo

class Student<T>{
   T age;
   Student(T age){
      this.age = age;
   }
   public void display() {
      System.out.println("Value of age: "+this.age);
   }
}
public class GenericsExample {
   public static void main(String args[]) {
      Student<Float> std1 = new Student<Float>(25.5f);
      std1.display();
      Student<String> std2 = new Student<String>("25");
      std2.display();
      Student<Integer> std3 = new Student<Integer>(25);
      std3.display();
   }
}

Output

Value of age: 25.5
Value of age: 25
Value of age: 25

Why do we need generics

Usage of generics in your code you will have the following advantages −

  • Type check at compile time − usually, when you use types (regular objects), when you pass an incorrect object as a parameter, it will prompt an error at the run time.

  • Whereas, when you use generics the error will be at the compile time which is easy to solve.

  • Code reuse − You can write a method or, Class or, interface using generic type once and you can use this code multiple times with various parameters.

  • For certain types, with formal types, you need to cast the object and use. Using generics (in most cases) you can directly pass the object of required type without relying on casting.

Updated on: 09-Sep-2019

46 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements