Why are generics used in Java
Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea that lets users to dynamically select the reference type that a function or class function Object() { [native code] } takes.
Java Generics is a group of related types or a group of related methods. Integer, String, and even user-defined types may be provided as parameters to classes, methods, and interfaces thanks to generics. Usually, classes like HashSet or HashMap utilize generics.
Making a class generic provides it type-safe, ensuring it can function with any datatype. Let's look at an example to help us understand generics.
In the following Java example we are defining a class named Employee whose constructor (parameterized) accepts an Integer object. While instantiating this class you can pass an integer object
class Employee{
Integer id;
Employee(Integer id){
this.id = id;
}
public void display() {
System.out.println("Value of id: "+this.id);
}
}
public class ExampleofGenerics {
public static void main(String args[]) {
Employee std = new Employee(1432);
std.display();
}
}
Output:

A compile time exception results when passing any other object to the function Object() of this class.
public static void main(String args[]) {
Employee std = new Employee("25");
std.display();
}
Compile time errorCompile
ExampleofGenerics.java:12: error: incompatible types: String cannot be converted to Integer
Employee std = new Employee("1432");
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
Employee ids can be supplied as (an object of) String values, Float values, Double values, etc. You must modify the function Object() if you wish to provide a value from another object.
class Employee{
String id;
Employee(String id){
this.id = id;
}
}
Or,
class Employee{
Float id;
Employee(Float id){
this.id = id;
}
}
They are referred to as parameterized types when you specify generic types since they may interact with any datatype. Generics do not support the usage of basic datatypes.
Creating generic types
To use generic parameter T or, GT as the basis for a generic type class
class Employee <T>{
T obj;
}
Where T (generic argument) stands for the datatype of the object you can supply to the function Object() of this class. During the compilation process, this will be decided.
You can or should select the type of the generic argument as when instantiating the class.
Employee<Float> obj = new Employee<Float>();
We may use generics to rephrase the above example as:
GenericsExample.java
class Employee<T>{
T id;
Employee(T id){
this.id = id;
}
public void display() {
System.out.println("Value of id: "+this.id);
}
}
public class GenericsExample {
public static void main(String args[]) {
Employee<Float> std = new Employee<Float>(1432.5f);
std.display();
}
}
Output

Now, while creating an instance of the Employee class, you may supply a parameter specifying the type of object you want.
GenericsExample.java
class Employee<T>{
T id;
Employee(T id){
this.id = id;
}
public void display() {
System.out.println("Value of id: "+this.id);
}
}
public class GenericsExample {
public static void main(String args[]) {
Employee<Float> ep1 = new Employee<Float>(1432.5f);
ep1.display();
Employee<String> ep2 = new Employee<String>("1432");
ep2.display();
Employee<Integer> ep3 = new Employee<Integer>(1432);
ep3.display();
}
}
Output

Why are generics necessary?
The following benefits come from using generics in your code:
- When you utilise types (ordinary objects), it normally results in an error at runtime if you supply the wrong object as a parameter. Type checking at build time prevents this from occuring.
- While using generics, the problem will occur during compilation and is simple to fix.
- Code reuse: By utilising generic types, you may define a method, class, or interface once and use it several times with different arguments.
- You must cast the object and utilise it for a number of formal kinds. The majority of the time, generics allow you to provide an object of the needed type directly without the need for casting.
- Generic classes allow you to create a variety of generic algorithms
Java Generics Types
Generic method: Generic Java methods accept an argument and execute an operation before returning some result. It functions precisely like a regular function, except generic methods have type arguments that are listed according to the actual type. This enables a broader use of the generic technique. Because the compiler handles type safety, programmers may write code more quickly because they are not required to do time-consuming, individual type casts.
Generic classes: A generic class has the exact same implementation as a non-generic class. The presence of a type parameter section is the only variation. There may be different parameter types, each separated by a comma. Parameterized classes or parameterized types are classes that take one or more parameters.