Stop 08 · Collections & GenericsTopics · 9/10

Generics & Bounded Types

Part of the Java Roadmap

In short

Generics are why List<String> refuses to accept an Integer and why you never cast what comes out of it. Once you can write your own generic classes and methods, you can build reusable code that is still type-safe.

Generics let classes and methods work with any type while staying type-safe, like List<String>. Bounded types (<T extends Number>) and wildcards (? extends, ? super) control which types are allowed.

The jaadu packs a row of steel tiffin boxes, each with a picture label of rice or snacks, and blocks a bowl of sambar from going into the rice box.

Think of it like this

Labelled tiffin boxes

A tiffin box labelled "Rice only" means nobody packs sambar into it by mistake, and whoever opens it knows exactly what is inside. That label is the type parameter. A bounded type is a stricter label like "Any dry snack": many things fit, but only from that family.

Watch it happen

? extends vs ? super

List<? extends Number>

  • Accepts List<Integer>, List<Double> and more
  • Safe to read items as Number
  • Cannot add (except null)
  • Use for producers you read from

List<? super Integer>

  • Accepts List<Integer>, List<Number>, List<Object>
  • Safe to add Integer values
  • Reading gives you only Object
  • Use for consumers you write into

PECS: Producer Extends, Consumer Super. Read from extends, write into super.

The big ideas

What you need to know

Errors at compile time

Generics catch wrong types while compiling instead of crashing with ClassCastException at runtime.

Generic classes

class Box<T> lets the caller pick the type: Box<String>, Box<Invoice>. T is a placeholder.

Generic methods

Put <T> before the return type, like static <T> T first(List<T> list). The compiler infers T.

Bounds narrow the type

<T extends Number> allows only Number subclasses, so you can call doubleValue() on T.

See it in code

Walk through the code

java
1import java.util.ArrayList;2import java.util.List;3 4public class GenericsDemo {5    static class Box<T> {6        private final T item;7        Box(T item) { this.item = item; }8        T get() { return item; }9    }10 11    static <T extends Number> double total(List<T> amounts) {12        double sum = 0;13        for (T a : amounts) sum += a.doubleValue();14        return sum;15    }16 17    static double sumAll(List<? extends Number> nums) {18        return nums.stream().mapToDouble(Number::doubleValue).sum();19    }20 21    static void addTokens(List<? super Integer> sink) {22        sink.add(101);23        sink.add(102);24    }25 26    public static void main(String[] args) {27        Box<String> gift = new Box<>("Rakhi");28        String g = gift.get();                              // no cast needed29 30        System.out.println(total(List.of(250, 499, 99)));   // 848.031        System.out.println(sumAll(List.of(1.5, 2.5)));      // 4.032 33        List<Number> tokens = new ArrayList<>();34        addTokens(tokens);                                  // Number is a super of Integer35        System.out.println(g + " " + tokens);               // Rakhi [101, 102]36    }37}

1/4Box<T> works for any type. Box<String> returns a String, so no cast is needed.

A generic class, a bounded generic method, and both kinds of wildcard in one small program.

Save yourself the pain

Common mistakes

Oops

Using raw types like List list = new ArrayList();

Do this instead

Always give the type: List<String>. Raw types switch off type checking and bring back casts.

Oops

Expecting List<Integer> to be accepted where List<Number> is required.

Do this instead

Generics are not covariant. Use List<? extends Number> as the parameter type instead.

Oops

Trying to write new T() or new T[10].

Do this instead

Type information is erased at runtime. Pass a Supplier<T> or a Class<T> if you need to create instances.

Your mission

Build a generic Pair

~25 min

Quick check

Which parameter type lets a method add Integer values into a list passed by the caller?

Go deeper

  1. 1Write a generic Box<T> class and a generic method.
  2. 2Write a method that sums any List<? extends Number>.
  3. 3Read about type erasure and why you can't do new T().

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge