☕ Java Intermediate

What are generics in Java?

Answer

Generics allow classes, interfaces, and methods to operate on types specified as parameters, providing type safety at compile time without requiring casts. Example: List<String> is a list that can only hold Strings — trying to add an Integer would be a compile error. Before generics (Java 1.4), collections held Object references requiring explicit casts everywhere and causing runtime ClassCastException. Generic methods: public <T> T getFirst(List<T> list). Bounded type parameters: <T extends Comparable<T>> restricts T to types that are comparable. Due to type erasure, generic type information is removed at compile time — at runtime, List<String> is just List.