Can you explain the concept of generics in Java? How do they improve type safety?
Generics in Java allow you to write classes, interfaces, and methods with a placeholder for the data type. They provide type safety by allowing you to specify the type of elements that a collection can hold, ensuring that type-related errors are caught at compile time rather than at runtime.
Example of generic class:
public class Box<T> { private T value; public void setValue(T value) { this.value = value; } public T getValue() { return value; } }