Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
4. Advanced Java & Frameworks
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

31. Generics: Type-Safe Templates

Building highly reusable, type-safe classes and methods.

Java Programming: From Zero to Enterprise
4. Advanced Java & Frameworks
February 22, 2026
62
A

[!NOTE] Generics were added in Java 5 to provide compile-time type checking and remove the risk of ClassCastException that plagued early developers. Understanding Generics is what separates junior developers from mid-level engineers.

Life before Generics

Before Generics, a standard Java ArrayList simply stored raw Object references. You could throw anything into it:

ArrayList myCart = new ArrayList(); // No type declared!
myCart.add("Apple");    // String
myCart.add(450);        // Integer
myCart.add(new Car());  // Car Object

// To retrieve the Apple, you had to manually "cast" it, praying it was actually a String.
String fruit = (String) myCart.get(0);

// If you accidentally grabbed index 1, your entire app crashed violently at Runtime!
String broken = (String) myCart.get(1); // ClassCastException: Cannot cast Integer to String

Life with Generics

Generics fix this by forcing you to specify the Type Parameter inside angle brackets <> .

// The compiler now strictly enforces that ONLY Strings enter this list!
ArrayList<String> myCart = new ArrayList<>();
myCart.add("Apple");
// myCart.add(450); // COMPILER ERROR! Refuses to run!

String fruit = myCart.get(0); // No manual casting required!

Creating Your Own Generic Class

You can use Generics in your own classes to create ultra-reusable architecture. Instead of hardcoding a type like String, you use a placeholder letter (conventionally T for Type).

// 1. We declare 'T' as a flexible placeholder when we write the blueprint.
public class Box<T> {
    private T contents;

    public void setContents(T item) {
        this.contents = item;
    }

    public T getContents() {
        return this.contents;
    }
}

public class Main {
    public static void main(String[] args) {
        // 2. We physically lock in the Type specifically when we instantiate the Box!
        Box<Integer> integerBox = new Box<Integer>();
        integerBox.setContents(42);
        
        Box<String> stringBox = new Box<String>();
        stringBox.setContents("Secret Document");
    }
}

[!CAUTION] Type Erasure: You cannot use primitive types like int inside angle brackets because Generics actively erase their type boundaries at runtime (a concept called Type Erasure) to maintain backwards compatibility with 1990s Java code. You MUST use wrapper classes like <Integer>!

Generics Make APIs Safer

Generics are not only for collections. They let you design reusable classes and methods while keeping compile-time type safety. A good generic API lets callers choose the type while the compiler prevents accidental mixing.

Generic Method Example

static <T> T first(List<T> items) {
    if (items.isEmpty()) {
        throw new IllegalArgumentException("List cannot be empty");
    }
    return items.get(0);
}

The same method works for List<String>, List<Integer>, or any other object type, while still returning the correct type.

Bounded Type Parameters

static <T extends Number> double sum(List<T> numbers) {
    double total = 0;
    for (T number : numbers) {
        total += number.doubleValue();
    }
    return total;
}

Common Mistakes

  • Using raw types such as List instead of List<String>.
  • Trying to use primitives directly, such as List<int>.
  • Adding too many type parameters and making APIs hard to read.
  • Expecting generic type information to always be available at runtime.

Mini Practice

Create a generic Pair<K, V> class with two fields and getters. Use it once for student name and marks, and once for product id and price.

Practice Lab: Generic Pair

Build a reusable generic class with two type parameters.

  1. Create a class Pair<K, V>.
  2. Add private final fields for key and value.
  3. Add a constructor and getters.
  4. Create Pair<String, Integer> for student name and marks.
  5. Create Pair<Integer, String> for product id and product name.

Goal: Practice reusable type-safe code without raw casts.

Revision Checkpoint

  • Generics: Add compile-time type safety.
  • Type parameter: Placeholder such as T, K, or V.
  • Raw type: Avoid plain List because it loses safety.
  • Wrapper types: Use Integer, not int, inside generics.
  • Type erasure: Generic type details are mostly removed at runtime.

Before the quiz: Explain why List<String> prevents a later cast error.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

mediumJava
Quiz: Generics
10 questions5 min
Lesson 1 of 11 in 4. Advanced Java & Frameworks
Next in 4. Advanced Java & Frameworks
32. Lambda Expressions & Functional Interfaces
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories