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.

Feb 22, 20263 views0 likes0 fires
18px

[!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>!

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
2 questions5 min

Continue Learning

32. Lambda Expressions & Functional Interfaces

Advanced
14 min

33. The Stream API: Functional Data Pipelines

Advanced
14 min

34. Optional: Beating the NullPointerException

Advanced
10 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 Java Programming: From Zero to EnterpriseAll Categories