What are Generics in Java? [closed]

Generics allow you to customize a “generic” method or class to whatever type you’re working with. For example, suppose you have a method that adds two numbers together. In order to work with the types themselves, you might have to create multiple versions of this method. For instance:

public int Add(int a, int b)

public double Add(double a, double b)

public float Add(float a, float b)

Generics allow you to create a single method that is customized for the type that invokes it.

public <T> T Add(T a, T b)

T is substituted for whatever type you use.

Leave a Comment