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.
Previous
What is the difference between fail-fast and fail-safe iterators?
Next
What is a thread in Java?
More Java Questions
View all →- Intermediate What is the Java Collections Framework?
- Intermediate What is the difference between ArrayList and LinkedList?
- Intermediate What is HashMap in Java and how does it work internally?
- Intermediate What is the difference between HashMap and HashTable in Java?
- Intermediate What is the difference between HashMap and LinkedHashMap?