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?

  1. Type Safety: Detect type errors at compile time

  2. Code Reusability: One class/method works with multiple types

  3. Eliminate Type Casting: Reduces runtime casting


 2. Generic Class Example


 

  • <T> is a type parameter.

  • Can replace T with 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

FeatureDescription
Generic ClassClass with type parameter <T>
Generic MethodMethod with type parameter <T>
Bounded TypeRestrict type using extends
WildcardsRepresent unknown type ?, ? extends, ? super
CollectionsWorks well with ArrayList<T>, HashMap<K,V>, etc.

Best Practices

  1. Use Generics for type safety and code reusability.

  2. Avoid using raw types (e.g., ArrayList without <T>).

  3. Use bounded types to restrict operations to compatible types.

You may also like...