Advantages and Disadvantages of Generics in Java

Generics in Java program was introduced in Java version 5. It is used to ensure the data type safety of objects. So, it constructs the code steady by detecting bugs at compile time.

Why do we need generics in Java?

When we write programs, errors occur. Some errors occur at run time while some errors occur at compile time. Those errors which occur at compile-time can be easily detected and rectified in the program. But, run time errors occur when an application is running in real-time and these errors cause a program to crash and it is hard to track them down. But these run time errors go unnoticed at compile time.

If we create an ArrayList without declaring the type of element.

For example:

The value 10 gets stored in the ArrayList but while adding the element “Java”, it shows ClassCastException. This is because as soon as we add the value 10 to the ArrayList, its datatype becomes <Integer>, so we try to add values of other datatypes, the program shows an error.

So, we use generics in it.

For example:

In the above code, ArrayList is only holding integer values. If we try to store other than integer values then it shows an error at compile time.

So, Java generic provides type – safety.

Generic types differ according to their arguments.

Program:


Output:

Advantages of Generics

There are basically three main advantages of generics in Java.

  • Generics provide type-safety. So, we can hold a single type of object in generics.
  • It provides a compile-time checker so it doesn’t show an error at runtime.
  • There is no necessity to typecast an object.

Disadvantages of Generics

We cannot use casts or instances with parameterized types.

Example:

We cannot assert static fields whose types are types of parameters.

Example:

We cannot personalize generic types with primitive types.

Example:

The catch or throw objects of parameterized types cannot be created.

Genric class doesn’t extend the throwable class directly or indirectly.

The throwable classes cannot be extended by generics directly or indirectly.

Example:

// Extends Throwable indirectly

// Extends Throwable directly

A method cannot grasp an instance of a type parameter:

So, that’s all about the advantages and disadvantages of generics in Java.

Leave a Comment

Your email address will not be published. Required fields are marked *