Sobes.tech
Middle

Что такое дженерики и для чего они используются?

sobes.tech AI

Answer from AI

Generics in Java are a mechanism that allows creating classes, interfaces, and methods with type parameters. They are used to ensure type safety and code reusability without the need to write separate versions for each data type.

For example, instead of creating a separate class for a list of integers and a list of strings, you can create a single generic class List<T>, where T is the type parameter:

public class Box<T> {
    private T value;

    public void set(T value) {
        this.value = value;
    }

    public T get() {
        return value;
    }
}

Box<Integer> intBox = new Box<>();
intBox.set(123);
Integer val = intBox.get();

This helps avoid type casting errors and makes the code more readable and flexible.