Junior — Middle
Can you explain the principle of generics in Java and how they allow creating universal classes and methods?
sobes.tech AI
Answer from AI
Generics in Java allow creating classes, interfaces, and methods that work with different data types while ensuring type safety at compile time. This means you can write universal code that is independent of a specific type and avoid type casting errors.
For example, the List<T> class is a list of elements of type T. When creating an instance, you can specify a particular type, such as List<String>, and the compiler guarantees that only strings will be added to the list.
Example of a generic class and method:
// Generic class with type parameter T
public class Box<T> {
private T value;
public void set(T value) {
this.value = value;
}
public T get() {
return value;
}
}
// Generic method
public static <U> void printBox(Box<U> box) {
System.out.println(box.get());
}
// Usage
Box<Integer> intBox = new Box<>();
intBox.set(123);
printBox(intBox); // Outputs: 123
Thus, generics allow writing more flexible and safe code, avoiding explicit type casts and runtime errors.