Sobes.tech
Senior

What are generics and why are they needed?

sobes.tech AI

Answer from AI

Generics (parametric types) in Java allow creating classes, interfaces, and methods that work with different data types while ensuring type safety during compilation.

Why are generics needed:

  • They allow writing reusable code that can work with various types.
  • They eliminate the need for casting, reducing the likelihood of errors.
  • They improve code readability and maintainability.

Example of using generics:

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 when creating an object.