Skip to content

Java Generics

1. What are generics in Java and why were they introduced?

Section titled β€œ1. What are generics in Java and why were they introduced?”

Generics allow us to write classes, interfaces, and methods that operate on specific data types while still being reusable. They were introduced to provide type safety and avoid runtime ClassCastException.

List<String> names = new ArrayList<>();

Now only String values can be added.


Generics ensure the type of data is checked at compile time. This prevents adding the wrong data type into a collection.

List<Integer> list = new ArrayList<>();
list.add("Hello"); // Compile-time error β†’ safe

3. What is the difference between generics in compile-time vs run-time?

Section titled β€œ3. What is the difference between generics in compile-time vs run-time?”
  • Compile-time: Generics enforce type checking.
  • Run-time: Generic type information is removed (due to type erasure).
List<Integer> a = new ArrayList<>();
List<String> b = new ArrayList<>();
System.out.println(a.getClass() == b.getClass()); // true

FeatureList<Object>List<?>
AcceptsAny objectAny generic list
Add elementsYesNo (except null)
Use caseInsert valuesRead-only access

5. What are bounded type parameters? Example using extends and super

Section titled β€œ5. What are bounded type parameters? Example using extends and super”

Bounded type parameters restrict the type that can be used.

<T extends Number> // Upper bound: T must be Number or its subclass
<? super Integer> // Lower bound: Type must be Integer or its parent

T can only be:

  • Number or its subclasses (Integer, Double, Float, etc.)
public class Test<T extends Number> { }

UseMeaningPurpose
? extends TAny subclass of TRead Only (Producer)
? super TAny superclass of TWrite Allowed (Consumer)

Easy rule: PECS β†’ Producer Extends, Consumer Super


A method that defines its own type parameter.

public static <T> void print(T value) {
System.out.println(value);
}

No, because generics work only with objects, and primitives are not objects. We use wrapper classes:

PrimitiveWrapper
intInteger
doubleDouble
List<int> // ❌
List<Integer> // βœ…

10. Can a generic class have multiple type parameters? Example <K, V>

Section titled β€œ10. Can a generic class have multiple type parameters? Example <K, V>”

Yes. Commonly used in Map implementations.

class Pair<K, V> {
K key;
V value;
}
Pair<String, Integer> p = new Pair<>();