Sobes.tech
Senior

What are parameterized types (generics) and what are they used for?

sobes.tech AI

Answer from AI

Parameterized types (generics) are a mechanism in programming languages that allows creating classes, interfaces, and methods that work with different data types without duplicating code. Instead of writing a separate class for each type, you can write a single universal class with a type parameter.

This increases code reusability and safety, as types are checked at compile time, reducing the likelihood of runtime errors.

Example in Java:

public class Box<T> {
    private T content;

    public void setContent(T content) {
        this.content = content;
    }

    public T getContent() {
        return content;
    }
}

// Usage:
Box<String> stringBox = new Box<>();
stringBox.setContent("Example");
String value = stringBox.getContent();

Here, T is a type parameter that is replaced with a specific type (e.g., String) when creating an object.

What are parameterized types (generics) and what are… - sobes.tech