Java Generics
📦 Java Generics
Generics in Java allow you to write classes, interfaces, and methods that can operate on any type of objects while providing compile-time type safety.
Introduced in Java 5
Helps avoid ClassCastException
Widely used in Collections Framework
1. Why Use Generics?
Type Safety: Detect type errors at compile time
Code Reusability: One class/method works with multiple types
Eliminate Type Casting: Reduces runtime casting
 2. Generic Class Example
<T>is a type parameter.Can replace
Twith any reference type (Integer, String, custom classes).
 3. Generic Method Example
<T>before return type declares a generic method.Can be used with arrays, collections, or any objects.
4. Generic Interface Example
Interfaces can also be generic.
 5. Bounded Generics
Restrict generic types to subclasses of a specific class.
Syntax:
<T extends Number>
Ensures only Number types (
Integer,Double,Float) can be used.
🔹 6. Wildcards (?) in Generics
Represents an unknown type
Useful in method parameters
? extends Number→ Upper bounded wildcard? super Integer→ Lower bounded wildcard
🧠Summary Table
| Feature | Description |
|---|---|
| Generic Class | Class with type parameter <T> |
| Generic Method | Method with type parameter <T> |
| Bounded Type | Restrict type using extends |
| Wildcards | Represent unknown type ?, ? extends, ? super |
| Collections | Works well with ArrayList<T>, HashMap<K,V>, etc. |
Best Practices
Use Generics for type safety and code reusability.
Avoid using raw types (e.g.,
ArrayListwithout<T>).Use bounded types to restrict operations to compatible types.
