Skip to lesson

Common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most generics mistakes fall into four groups: raw types and casts, primitives and wrappers, bounds and wildcards, and the limits of erasure. The Java compiler (javac) catches most of them at once; the few that compile are worth knowing by heart.

Mistakes and fixes at a glance

The most expensive slip is a raw type. One missing <String> in a parameter switches the Java compiler's checks off, and the wrong value crashes the app much later, in another method.

Example 1 · Bug: one missing type argument

RawBugDemo.javaJava
import java.util.ArrayList;
public class RawBugDemo {    static void addToOrder(ArrayList order) {        order.add(2);    }
    public static void main(String[] args) {        ArrayList<String> order = new ArrayList<>();        order.add("Keyboard");        addToOrder(order);        for (String product : order) {            System.out.println("Ship: " + product);        }    }}
Sample output (the program stops with an exception)
Ship: Keyboard
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
	at RawBugDemo.main(RawBugDemo.java:12)

What this code does

  • addToOrder takes a raw ArrayList, so order.add(2) passes the Java compiler with only an "unchecked" warning, and the number 2 lands in an ArrayList<String>.
  • The crash comes later, in main, on the hidden (String) cast of the for-each loop. Write ArrayList<String> order in the parameter and the Java compiler stops add(2) at once.

Review: Why generics? (opens in a new tab). The other common mistakes, each with its error and the fix:

Mistakes that compile

Two bugs give no error at all: == on two wrapper objects, and unboxing an Integer that is still null. Both pass the Java compiler; only a run shows them.

Example 2 · Two silent bugs and their fixes

SilentBugsDemo.javaJava
class Box<T> {    private T value;
    void set(T value) {        this.value = value;    }
    T get() {        return value;    }}
public class SilentBugsDemo {    public static void main(String[] args) {        Box<Integer> ordered = new Box<>();        Box<Integer> paid = new Box<>();        ordered.set(25000);        paid.set(25000);        System.out.println("Paid in full? " + (ordered.get() == paid.get()));        System.out.println("Paid in full? " + ordered.get().equals(paid.get()));
        Box<Integer> discount = new Box<>();        Integer d = discount.get();        int off = (d == null) ? 0 : d;        System.out.println("Discount: Rs. " + off);    }}
Output
Paid in full? false
Paid in full? true
Discount: Rs. 0

What this code does

  • 25000 is outside the Integer cache (-128 to 127), so the two boxes hold two different objects and == says false. equals compares the values and says true.
  • discount was never set. Keeping the value as Integer d and checking d == null before unboxing avoids the NullPointerException that int off = discount.get(); would throw.

Both come from wrappers being objects. Compare values with equals, and check for null before a wrapper turns into an int. Review: Write a generic class (opens in a new tab)

Spot the bug

Each snippet below looks almost right. Read what it should do, tap the wrong line, then check the fix. Ask: is it an object type, does the method declare its own T, what does the bound allow, and does the list give or take values?

Find the bug

Find the generics bug

Select the line that is wrong.

Store the price 6000 in a box.

Round 1 of 6

Trace before you guess

When a generic call surprises you, trace it: first work out what the Java compiler infers for T, then follow the values. Here a copy method moves today's bills into a report that already holds a fee.

Trace the code

Trace a copy between two lists

import java.util.ArrayList;
public class CopyTrace {
static <T> void copy(ArrayList<? extends T> from, ArrayList<? super T> to) {
for (T item : from) {
to.add(item);
}
}
public static void main(String[] args) {
ArrayList<Integer> bills = new ArrayList<>();
bills.add(12000);
bills.add(9500);
ArrayList<Number> report = new ArrayList<>();
report.add(99.5);
copy(bills, report);
System.out.println(report);
System.out.println("Items: " + report.size());
}
}

Variables

bills
[]

Output

(nothing printed yet)

Line 11bills is an ArrayList<Integer>, empty for now.

Step 1 of 10

Example 3 · Everything together: a generic Result

ResultDemo.javaJava
class Result<T> {    private final T value;    private final String error;
    private Result(T value, String error) {        this.value = value;        this.error = error;    }
    static <T> Result<T> ok(T value) {        return new Result<>(value, null);    }
    static <T> Result<T> fail(String error) {        return new Result<>(null, error);    }
    boolean isOk() {        return error == null;    }
    T get() {        return value;    }
    String error() {        return error;    }}
class Product {    String name;    int price;
    Product(String name, int price) {        this.name = name;        this.price = price;    }}
public class ResultDemo {    static Result<Product> find(Product[] catalog, String name) {        for (Product m : catalog) {            if (m.name.equals(name)) {                return Result.ok(m);            }        }        return Result.fail(name + " is not in the catalog");    }
    public static void main(String[] args) {        Product[] catalog = { new Product("Keyboard", 2000), new Product("Headphones", 6000) };        String[] wanted = { "Keyboard", "Drone" };        for (String w : wanted) {            Result<Product> r = find(catalog, w);            if (r.isOk()) {                System.out.println("Added " + r.get().name + ", Rs. " + r.get().price);            } else {                System.out.println("Sorry: " + r.error());            }        }    }}
Output
Added Keyboard, Rs. 2000
Sorry: Drone is not in the catalog

What this code does

  • Result<T> is a generic class with a private constructor and two static generic factory methods, ok and fail, each declaring its own <T>.
  • In return Result.fail(...), no argument has type T, so the Java compiler infers T = Product from the return type Result<Product>.
  • The caller gets either a Product from get(), with no cast, or an error message: one type for both outcomes.

Module quiz

Questions from the whole module. Your first answer is your score.

Problems

Graded easy to hard, using everything from this module.

Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.

Exercise 1· Easy

Write Pair<K, V> with a toString() that returns (first, second). Print a pair of a product and its price, and a pair of a ticket and a name.

Expected output
(Keyboard, 2000)
(101, Priya)

Exercise 2· Easy

This program does not compile. Fix the two type arguments so it prints the output.

StoreStatus.javaJava
class Box<T> {    private T value;
    void set(T value) {        this.value = value;    }
    T get() {        return value;    }}
public class StoreStatus {    public static void main(String[] args) {        Box<int> units = new Box<>();        units.set(120);        Box<boolean> open = new Box<>();        open.set(true);        System.out.println("Units: " + units.get());        System.out.println("Store open: " + open.get());    }}
Expected output
Units: 120
Store open: true

Exercise 3· Medium

This method counts how often a ticket appears, but it prints 0 for ticket 500, which appears twice. Find the bug and fix it so it prints the output.

TicketCount.javaJava
public class TicketCount {    static <T> int countMatches(T[] items, T target) {        int c = 0;        for (T item : items) {            if (item == target) {                c++;            }        }        return c;    }
    public static void main(String[] args) {        Integer[] tickets = { 500, 501, 500 };        System.out.println("Ticket 500 appears " + countMatches(tickets, 500) + " times");    }}
Expected output
Ticket 500 appears 2 times

Exercise 4· Medium

Write static <T extends Comparable<T>> boolean isSorted(T[] items) that returns true when each item is less than or equal to the next. Check the prices { 1200, 2500, 4000, 6000 } and the names { "Meera", "Aarav", "Rahul" }.

Expected output
Prices sorted? true
Names sorted? false

Exercise 5· Medium

Write static void addRange(ArrayList<? super Integer> list, int from, int to) and static double average(ArrayList<? extends Number> values). Fill an ArrayList<Number> with 1 to 4, add the Double 2.5 yourself, then print the list and its average.

Expected output
Numbers: [1, 2, 3, 4, 2.5]
Average: 2.5

Exercise 6· Medium

This Stack<T> does not compile: "generic array creation". Store the items in an Object[] instead and cast in pop(). Push three products, pop two and print as shown.

StackFix.javaJava
class Stack<T> {    private T[] items = new T[5];    private int size = 0;
    void push(T item) {        items[size] = item;        size++;    }
    T pop() {        size--;        return items[size];    }
    int size() {        return size;    }}
public class StackFix {    public static void main(String[] args) {        Stack<String> units = new Stack<>();        units.push("Keyboard");        units.push("Camera");        units.push("Mouse");        System.out.println("Popped: " + units.pop());        System.out.println("Popped: " + units.pop());        System.out.println("Left: " + units.size());    }}
Expected output
Popped: Mouse
Popped: Camera
Left: 1

Exercise 7· Hard

Write a bounded generic class Catalog<T extends Product> that holds a T[] and has T cheapest() and int total(). Bound by your own class: Product has a name and a price. Use a Catalog<Product> with Cable Rs. 1200, Charger Rs. 1500 and Headphones Rs. 6000.

Expected output
Cheapest: Cable, Rs. 1200
Total: Rs. 8700

Exercise 8· Hard

Write interface Check<T> { boolean test(T t); } and a generic class Found<T> with a value (may be null) and boolean isFound(). Write static <T> Found<T> firstMatch(T[] items, Check<T> check). With lambdas, find the first product under Rs. 2000 and the first ticket above 200.

Expected output
Found: Charger, Rs. 1500
No ticket above 200

Interview questions

Questions interviewers ask on this topic.

What's next

You finished the preview of Generics

Java Programming has 26 sections, 252 modules and 1949 lessons. An account opens every lesson and saves your progress.

Finish up

Mark complete & continue

Next: Why collections, not arrays?