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
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); } }}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
addToOrdertakes a rawArrayList, soorder.add(2)passes the Java compiler with only an "unchecked" warning, and the number 2 lands in anArrayList<String>.- The crash comes later, in
main, on the hidden(String)cast of the for-each loop. WriteArrayList<String> orderin the parameter and the Java compiler stopsadd(2)at once.
Review: Why generics? (opens in a new tab). The other common mistakes, each with its error and the fix:
unexpected type ... required: reference, found: int→Box<int>→ use the wrapper,Box<Integer>. Review: Write a generic class (opens in a new tab)non-static type variable T cannot be referenced from a static context→ a static method or field uses the class'sT→ give the method its own<T>. Review: Generic methods (opens in a new tab)method firstOf ... cannot be applied to given typeswithint[]→T[]needs an object array →Integer[]. Review: Generic methods (opens in a new tab)cannot find symbol ... method compareTo(T)→ a plainT→ add a bound,<T extends Comparable<T>>. Review: Bounded types (opens in a new tab)ArrayList<Integer> cannot be converted to ArrayList<Number>→ generics are invariant →? extends Numberfor a reader. Review: Wildcards (opens in a new tab)int cannot be converted to CAP#1onadd→ writing through? extends→? super Integer. Review: Wildcards (opens in a new tab)generic array creation,name clash ... have the same erasure→ limits of erasure → anObject[]with a cast; different method names. Review: Type erasure (opens in a new tab)
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
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); }}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
==saysfalse.equalscompares the values and saystrue. discountwas never set. Keeping the value asInteger dand checkingd == nullbefore unboxing avoids theNullPointerExceptionthatint 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 6Trace 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
Variables
- bills
- []
Output
(nothing printed yet)Line 11bills is an ArrayList<Integer>, empty for now.
Example 3 · Everything together: a generic Result
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()); } } }}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,okandfail, each declaring its own<T>.- In
return Result.fail(...), no argument has typeT, so the Java compiler infersT = Productfrom the return typeResult<Product>. - The caller gets either a
Productfromget(), 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.
(Keyboard, 2000) (101, Priya)
Exercise 2· Easy
This program does not compile. Fix the two type arguments so it prints the output.
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()); }}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.
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"); }}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" }.
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.
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.
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()); }}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.
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.
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?