0
0
JavaConceptBeginner · 3 min read

What is Type Parameter in Java Generics Explained

A type parameter in Java generics is a placeholder for a data type that is specified when creating an instance of a generic class or method. It allows you to write flexible and reusable code that works with different types while maintaining type safety.
⚙️

How It Works

Think of a type parameter as a blank label on a box that you can fill with any type you want later. When you write a generic class or method, you use a type parameter as a placeholder instead of a specific type like Integer or String. This means the same code can work with many types without rewriting it.

For example, if you have a box that can hold anything, the type parameter lets you decide what kind of item the box will hold when you actually use it. This helps avoid mistakes because the compiler checks that you only put the right type of item in the box.

💻

Example

This example shows a generic class with a type parameter T. It stores a value of type T and returns it. When creating an object, you specify the actual type.

java
public class Box<T> {
    private T value;

    public Box(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }

    public static void main(String[] args) {
        Box<String> stringBox = new Box<>("Hello");
        Box<Integer> intBox = new Box<>(123);

        System.out.println(stringBox.getValue());
        System.out.println(intBox.getValue());
    }
}
Output
Hello 123
🎯

When to Use

Use type parameters when you want to create classes or methods that can work with different types without losing type safety. This is common in collections like lists, maps, or any container that holds objects.

For example, if you write a method to find the largest item in a list, using a type parameter lets you use the same method for lists of numbers, strings, or any objects that can be compared.

Key Points

  • Type parameters are placeholders for types used in generic classes or methods.
  • They enable code reuse and type safety by allowing the compiler to check types.
  • You specify the actual type when creating an instance or calling a method.
  • Commonly used in collections and utility classes.

Key Takeaways

Type parameters let you write flexible, reusable code that works with any type.
They act as placeholders replaced by actual types when you use the generic class or method.
Using type parameters helps catch type errors at compile time.
Generics improve code safety and reduce the need for casting.
They are essential for working with collections and custom generic classes.