Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Generics

Java Generics: Type-Safe Containers

A box of Object takes "Java Basics" and 42, and the String cast on the way out crashes. Box<T> lets the label decide what goes in, so javac stops the 42 before the program runs. Plus Pair<K, V>, the diamond, type erasure and a raw list next to a typed one.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Generics

What you will learn

  • Explain why a box of Object needs casts and can crash with ClassCastException
  • Write a generic class Box<T> and use it with different types
  • Use two type parameters and the diamond operator
  • Explain type erasure and why a typed list fails at compile time instead of run time

Before you start

  • Java ArrayList
  • Java wrapper classes and autoboxing

The whole idea of generics fits in one line: the label on the box decides what may go in. To see why that matters, start with a box that has no label.

A box that takes anything

package org.studyeasy.s04l05;

// The old way: one box for anything
public class ObjectBox {
    private Object item;

    public void set(Object item) {
        this.item = item;
    }

    public Object get() {
        return item;               // you get back a plain Object
    }
}
ObjectBox box = new ObjectBox();
box.set("Java Basics");
String title = (String) box.get();     // cast every time
System.out.println("Course: " + title);

box.set(42);                           // compiler says fine
try {
    String oops = (String) box.get();  // 42 is not a String
    System.out.println(oops);
} catch (ClassCastException e) {
    System.out.println("Crash: "
            + e.getClass().getSimpleName());
}
Course: Java Basics
Crash: ClassCastException

Object is the parent of every class, so the box holds anything. That's the problem. get returns a plain Object, so every read needs a cast. The 42 goes in without complaint, and the String cast on the way out fails because it's an Integer inside. You only find out while the program runs; without the catch, Java stops with the ClassCastException.

The label decides what may go in

package org.studyeasy.s04l05;

// T is a type parameter: the caller picks the real type
public class Box<T> {
    private T item;

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

    public T get() {
        return item;               // comes back as T, no cast
    }
}

T is a type parameter, a placeholder for the real type. Write Box<String> and T becomes String: that's the label.

Box<String> course = new Box<>();
course.set("Java Basics");
String title = course.get();           // no cast
System.out.println("Course: " + title);

Box<Integer> seats = new Box<>();
seats.set(30);
int left = seats.get() - 4;            // unboxed to int
System.out.println("Seats left: " + left);

boolean same = course.getClass() == seats.getClass();
System.out.println("Same class at runtime? " + same);
Course: Java Basics
Seats left: 26
Same class at runtime? true

Box<String> takes only Strings, and get already returns a String. Box<Integer> takes only Integers; 30 comes back and is unboxed, so 30 minus 4 is 26. Add course.set(42) and javac stops: int cannot be converted to String. The 42 never gets into the box.

Why is "same class" true? Javac checks the labels while compiling, then erases them. This is called type erasure. At run time both boxes are the same Box class. The labels are for the compiler.

Two parameters, and the diamond

package org.studyeasy.s04l05;

// Two type parameters: K for the key, V for the value
public class Pair<K, V> {
    private final K key;
    private final V value;

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    public K getKey() { return key; }
    public V getValue() { return value; }

    public String toString() {
        return key + "=" + value;
    }
}
Pair<String, Integer> asha =
        new Pair<String, Integer>("Asha", 87);  // spelled out
Pair<String, Integer> ben = new Pair<>("Ben", 92);  // diamond

System.out.println(ben.getKey() + " scored " + ben.getValue());

List<Pair<String, Integer>> grades = new ArrayList<>();
grades.add(asha);
grades.add(ben);
System.out.println("Grades: " + grades);
Ben scored 92
Grades: [Asha=87, Ben=92]

Each type parameter gets its own label: K becomes String and V becomes Integer. For Asha the types are written out in full; for Ben the empty angle brackets, the diamond, let Java copy them from the left side. getKey returns a String and getValue an Integer, with no casts anywhere. new Pair<>("Cara", "high") fails, because "high" isn't an Integer.

Where does the 42 get caught?

List raw = new ArrayList();            // no type: anything goes
raw.add("Asha");
raw.add(42);                           // compiler says fine
try {
    for (Object o : raw) {
        String name = (String) o;
        System.out.println("Student: " + name);
    }
} catch (ClassCastException e) {
    System.out.println("Crash: "
            + e.getClass().getSimpleName());
}

List<String> names = new ArrayList<>();
names.add("Asha");
names.add("Ben");
System.out.println("Typed: " + names);
Student: Asha
Crash: ClassCastException
Typed: [Asha, Ben]

(The real file puts @SuppressWarnings({"rawtypes", "unchecked"}) on main to quiet the compiler's warnings about the raw list.)

Two lanes through two stages, compile with javac then run with java. Raw List: 42 passes javac and breaks at run time with ClassCastException. List of String: 42 is stopped at javac with a compile error, before the program runs. javac java raw List List<String> add(42) add(42) ClassCastException compile error a run-time error can reach users
A raw list fails while it runs; a typed list fails before it runs.

The raw List has no label, so Asha and 42 both go in, and the cast in the loop breaks on 42 at run time. List<String> checks every add, so names.add(42) is a compile error: incompatible types. A compile error is the better kind, because a run-time error can reach your users.

Recap

IdeaExample
Box of Objecttakes anything; every read needs a cast; wrong cast crashes at run time
Generic classclass Box<T>; the caller picks T
Two parametersPair<K, V>
Diamondnew Pair<>("Ben", 92)
Type erasurelabels are checked, then erased: one Box class at run time

Next: methods with their own type parameter, bounds and wildcards in generic methods, bounded types and wildcards.

Keep going in Java · 58 of 79

Previous
Java try-with-resources and Clean Error Handling
Next post
Java Generic Methods, Bounded Types and Wildcards
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Generic Methods, Bounded Types and Wildcards

Three copies of lastOf become one <T> T lastOf(List<T>). T extends Number lets largest call doubleValue and refuses a list of String. A List<? extends Number> totals seats and fees but won't take an add, and a List<? super Integer> accepts 30 and 45.

On this page

  • A box that takes anything
  • The label decides what may go in
  • Two parameters, and the diamond
  • Where does the 42 get caught?
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.