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 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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Generics

What you will learn

  • Write one generic method that works for a list of any type
  • Restrict a type parameter with a bound such as T extends Number
  • Read from a List<? extends Number> and explain why you can't add to it
  • Add values to a List<? super Integer>, and pick T, extends or super for a job

Before you start

  • Java generics: type-safe containers
  • Java methods and overloading

This lesson covers three things: one method that works for any list, a rule for what it accepts, and a question mark that means "some type".

One method, any list

Imagine three methods, lastName, lastScore and lastFee, for lists of String, Integer and Double. The body is the same in each: return items.get(items.size() - 1);. A generic method writes it once.

package org.studyeasy.s04l06;

import java.util.List;

public class Ex01_GenericMethod {
    // <T> before the return type makes the method generic
    static <T> T lastOf(List<T> items) {
        return items.get(items.size() - 1);
    }

    public static void main(String[] args) {
        List<String> students = List.of("Asha", "Ravi", "Neha");
        List<Integer> scores = List.of(72, 85, 91);
        List<Double> fees = List.of(49.5, 19.99, 75.0);

        String lastName = lastOf(students);     // T is String
        Integer lastScore = lastOf(scores);     // T is Integer
        Double lastFee = lastOf(fees);          // T is Double

        System.out.println("Last name: " + lastName);
        System.out.println("Last score: " + lastScore);
        System.out.println("Last fee: " + lastFee);
    }
}
Last name: Neha
Last score: 91
Last fee: 75.0

The <T> right before the return type is what makes the method generic. In the signature, T is a blank, and each call fills it in from the list you pass: String for students, Integer for scores, Double for fees. Integer wrong = lastOf(students); doesn't compile, because T is String there.

A bound: T must be a Number

// T must be a Number, so doubleValue() is allowed
static <T extends Number> T largest(List<T> values) {
    T best = values.get(0);
    for (T value : values) {
        if (value.doubleValue() > best.doubleValue()) {
            best = value;
        }
    }
    return best;
}

List<Integer> seats = List.of(30, 45, 25);
List<Double> fees = List.of(49.5, 19.99, 75.0);
System.out.println("Most seats: " + largest(seats));
System.out.println("Top fee: " + largest(fees));
Most seats: 45
Top fee: 75.0

T extends Number is the bound: only number types can be T. Integer, Double and Long all qualify. Because T is always a Number, doubleValue() is allowed. The loop keeps the biggest so far. Pass a List<String> and javac refuses it with incompatible bounds: T would be String, but the upper bound is Number. The bound is a rule at the door.

? extends Number: read from it

// ? extends Number: a list of any kind of Number. Read from it.
static double total(List<? extends Number> amounts) {
    double sum = 0;
    for (Number amount : amounts) {   // every item is a Number
        sum += amount.doubleValue();
    }
    return sum;
}

List<Integer> seats = List.of(30, 45, 25);
List<Double> fees = List.of(49.5, 20.0, 30.25);
System.out.println("Seats: " + total(seats));
System.out.println("Fees: " + total(fees));
Seats: 100.0
Fees: 99.75

Instead of T, the parameter uses a wildcard, a question mark. List<? extends Number> is a list of some kind of Number, and we don't know which. Every item is a Number, so reading is always safe, and one method handles both lists. But amounts.add(10) inside the method doesn't compile. If the list passed in is a List<Double>, an Integer 10 would be wrong, and Java can't tell which type would be safe. The error mentions CAP#1, the compiler's name for that unknown type.

? super Integer: put values in

// ? super Integer: any list that can hold an Integer. Write to it.
static void addSeats(List<? super Integer> target) {
    target.add(30);
    target.add(45);
}

List<Integer> seats = new ArrayList<>();
List<Number> amounts = new ArrayList<>();
amounts.add(19.99);

addSeats(seats);     // a List<Integer>
addSeats(amounts);   // a List<Number> works too

System.out.println("seats:   " + seats);
System.out.println("amounts: " + amounts);
seats:   [30, 45]
amounts: [19.99, 30, 45]

List<? super Integer> means any list that can hold an Integer: a List of Integer, Number or Object. So adding Integers inside is safe. Both calls work, and the 19.99 stays. addSeats(new ArrayList<String>()) fails, because a String list can't hold an Integer.

A type ladder: Object at the top, Number below it, Integer and Double below Number. List of ? extends Number accepts lists of Number, Integer or Double and lets you read items as Number. List of ? super Integer accepts lists of Integer, Number or Object and lets you add Integers. ObjectNumberIntegerDouble ? extends Number Number, Integer,Double lists read only ? super Integer Integer, Number,Object lists add Integers
extends looks down the ladder and reads; super looks up the ladder and writes.

Recap

WriteUse it when
<T> T lastOf(List<T>)you want the same type back
<T extends Number>only some types should be allowed
List<? extends Number>you only read from the list
List<? super Integer>you put values into the list

An AI will often pick the right one for you, but knowing these lets you read the code it writes. Generics show up again in every collection that follows, starting with sets.

Keep going in Java · 59 of 79

Previous
Java Generics: Type-Safe Containers
Next post
Java Lambdas and Functional Interfaces
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 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.

On this page

  • One method, any list
  • A bound: T must be a Number
  • ? extends Number: read from it
  • ? super Integer: put values in
  • 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.