What are type parameters in Java?

Overview

We can use Java Generics to specify one or more type parameters to classes and methods. This allows for more flexibility and robust code. We can make a class or method work with any type that meets specific criteria by specifying a type parameter. This makes our code more reusable and easier to maintain.

Syntax

For example, consider the following class:

public class MyClass<T> {
// ...
}
Syntax of using type parameters in Java

Parameters

This class has a type parameter called T. This means that the class can work with any type that is specified when the class is instantiated.

Example

For example, we could create an instance of MyClass like this:

MyClass<String> myObj = new MyClass<String>();
Instantiating a class using String type parameter

In the above example, we are saying that our MyClass object will work with the String objects. We could also create an instance of MyClass like this:

MyClass<Integer> myObj = new MyClass<Integer>();
Instantiating a class using Integer type parameter.

In this example, we say that our MyClass object will work with the Integer objects. We can use any type we want as the type parameter, including our own custom classes.

We use type parameters because it makes our code more flexible and reusable. For example, consider a method that sorts an array of objects:

import java.util.Arrays;
class Sorter<T> {
public void sort(T[] arr) {
Arrays.sort(arr);
}
public static void main(String args[] ) {
Sorter<Integer> intSorter = new Sorter<>();
Integer[] intArr = new Integer[]{3,2,1};
intSorter.sort(intArr);
Sorter<String> strSorter = new Sorter<>();
String[] strArr = new String[]{"c", "b", "a"};
strSorter.sort(strArr);
System.out.println(Arrays.toString(intArr));
System.out.println(Arrays.toString(strArr));
}
}

The sort() method can sort an array of any type that is specified when the method is called. If we didn't use type parameters, we would have to write a separate sort method for each type of array we wanted to sort.

With type parameters, we can write one sort method that can be used for both String and Integer arrays.