Advanced Java
Generics
Complete lesson for Generics using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.
Basics — Generics
Section: Advanced Java. Write type-safe, reusable code once: generic classes, methods, interfaces, bounded types, wildcards, PECS, and type erasure — with real-life examples.
What are generics?
- Generics let you write a class, interface, or method once with a type parameter (like
T) and use it safely with many types. - The actual type is given when you use it:
List<String>,Box<Integer>,Map<String, Double>. - The compiler checks types for you, so wrong types are caught at compile time instead of crashing at runtime.
- Real life: storage boxes with labels. A box labelled "Books" accepts only books, so you never pull out a shoe when you expect a book. One box design works for books, toys, or clothes.
- Introduced in Java 5. The whole Collections Framework (
List<E>,Map<K, V>) is generic.
import java.util.ArrayList;
import java.util.List;
public class WhyGenerics {
public static void main(String[] args) {
// Without generics (raw type): anything goes in, casts needed, errors at runtime
List raw = new ArrayList();
raw.add("Asha");
raw.add(42); // compiles: no type check
try {
String name = (String) raw.get(1); // ClassCastException at runtime
System.out.println(name);
} catch (ClassCastException e) {
System.out.println("Runtime crash: " + e.getClass().getSimpleName());
}
// With generics: the compiler protects you
List<String> names = new ArrayList<>();
names.add("Asha");
// names.add(42); // compile error: int cannot be converted to String
String first = names.get(0); // no cast needed
System.out.println("Safe: " + first);
}
} Why we need generics
| Benefit | Meaning | Example |
|---|---|---|
| Type safety | Wrong types are rejected at compile time | List<String> cannot add(42) |
| No casting | The compiler inserts casts for you | String s = names.get(0); |
| Code reuse | One class or method works for many types | Box<Book>, Box<Toy>, Box<Integer> |
| Readable APIs | Types document what goes in and comes out | Map<String, List<Order>> |
| Early bug detection | Errors appear while compiling, not in production | No surprise ClassCastException |
| Generic algorithms | Sort, search, and copy any comparable type | Collections.sort(List<T>) |
Differences between code without generics and with generics
| Point | Without generics (raw types) | With generics |
|---|---|---|
| Declaration | List list = new ArrayList(); | List<String> list = new ArrayList<>(); |
| Type checking | None: any object can be added | Compile-time: only the declared type |
| Reading values | Needs an explicit cast | No cast needed |
| When errors appear | At runtime (ClassCastException) | At compile time |
| Compiler warnings | Unchecked / raw type warnings | None |
| Readability | Unclear what the list holds | Type is visible in the declaration |
| Use today | Only for legacy code | Always in new code |
Type parameter naming conventions
- Type parameters are single uppercase letters by convention, so they are easy to tell apart from class names.
| Letter | Stands for | Used in |
|---|---|---|
T | Type | Box<T>, Optional<T> |
E | Element | List<E>, Set<E> |
K | Key | Map<K, V> |
V | Value | Map<K, V> |
N | Number | Stats<N extends Number> |
R | Result / return type | Function<T, R> |
S, U, V | Second, third, fourth types | Triple<T, U, V> |
Generic class
- Add the type parameter after the class name:
class Box<T>. UseTlike any type inside the class. - Create objects with a real type:
Box<String> b = new Box<>("Hello");. - Real life: a courier parcel box. The same box design can carry a phone, a book, or shoes, and the label says what is inside.
class Parcel<T> {
private final T item;
private final String to;
Parcel(T item, String to) {
this.item = item;
this.to = to;
}
T open() {
return item;
}
String label() {
return "Parcel for " + to + " containing " + item.getClass().getSimpleName();
}
}
class Book {
final String title;
Book(String title) { this.title = title; }
}
public class CourierDemo {
public static void main(String[] args) {
Parcel<Book> p1 = new Parcel<>(new Book("Head First Java"), "Asha");
Parcel<Integer> p2 = new Parcel<>(500, "Ravi"); // autoboxed Integer
Book b = p1.open(); // no cast needed
int amount = p2.open(); // auto-unboxed
System.out.println(p1.label() + ": " + b.title);
System.out.println(p2.label() + ": " + amount);
// Book wrong = p2.open(); // compile error
}
} Generic class with multiple type parameters
- Separate parameters with commas:
class Pair<K, V>. - Real life: a locker number and the bag stored inside, or a student roll number and the student name.
class Pair<K, V> {
private final K key;
private final V value;
Pair(K key, V value) {
this.key = key;
this.value = value;
}
K getKey() { return key; }
V getValue() { return value; }
@Override
public String toString() {
return key + " = " + value;
}
}
public class PairDemo {
public static void main(String[] args) {
Pair<Integer, String> student = new Pair<>(101, "Asha");
Pair<String, Double> price = new Pair<>("Laptop", 54999.0);
Pair<String, Boolean> feature = new Pair<>("Dark mode", true);
System.out.println(student); // 101 = Asha
System.out.println(price); // Laptop = 54999.0
System.out.println(feature); // Dark mode = true
int roll = student.getKey(); // no cast
System.out.println("Roll number: " + roll);
}
} Generic methods
- A method can declare its own type parameter before the return type:
static <T> void printAll(T[] items). - It works even inside a non-generic class. The compiler usually infers
Tfrom the arguments. - You can give the type explicitly (a type witness):
Util.<String>firstOf(list). - Real life: a photocopier copies any document, a bill, a certificate, or a photo, without needing a different machine for each.
import java.util.List;
public class GenericMethods {
static <T> void printAll(T[] items) {
for (T item : items) {
System.out.print(item + " ");
}
System.out.println();
}
static <T> T firstOf(List<T> list) {
return list.isEmpty() ? null : list.get(0);
}
static <K, V> String describe(K key, V value) {
return key + " -> " + value;
}
public static void main(String[] args) {
Integer[] marks = { 87, 92, 78 };
String[] cities = { "Hyderabad", "Pune", "Chennai" };
printAll(marks); // T = Integer
printAll(cities); // T = String
String first = firstOf(List.of("Java", "Python")); // T inferred as String
System.out.println(first);
System.out.println(GenericMethods.<Integer>firstOf(List.of(5, 6))); // type witness
System.out.println(describe("PIN", 500081));
}
} Generic interfaces
- Interfaces can be generic too:
interface Repository<T, ID>. - An implementing class either fixes the type (
class StudentRepo implements Repository<Student, Integer>) or stays generic (class MemoryRepo<T, ID> implements Repository<T, ID>). - JDK examples:
Comparable<T>,Comparator<T>,Iterable<T>,Function<T, R>.
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
interface Repository<T, ID> {
void save(ID id, T item);
Optional<T> findById(ID id);
int count();
}
class MemoryRepository<T, ID> implements Repository<T, ID> {
private final Map<ID, T> store = new HashMap<>();
public void save(ID id, T item) { store.put(id, item); }
public Optional<T> findById(ID id) { return Optional.ofNullable(store.get(id)); }
public int count() { return store.size(); }
}
record Student(String name, int marks) { }
public class RepoDemo {
public static void main(String[] args) {
Repository<Student, Integer> students = new MemoryRepository<>();
students.save(1, new Student("Asha", 91));
students.save(2, new Student("Ravi", 84));
System.out.println(students.findById(1).map(Student::name).orElse("none")); // Asha
System.out.println(students.findById(9).isPresent()); // false
System.out.println("Total: " + students.count()); // 2
}
} Diamond operator and type inference
- Since Java 7 you can write
new ArrayList<>()and the compiler fills in the type from the left side. - Since Java 9 the diamond also works with anonymous classes when the inferred type is denotable.
- With
var(Java 10), put the type on the right:var map = new HashMap<String, Integer>();. Writingvar list = new ArrayList<>();givesArrayList<Object>, which is usually not what you want.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DiamondDemo {
public static void main(String[] args) {
Map<String, List<Integer>> marks = new HashMap<>(); // diamond: types inferred
marks.put("Asha", new ArrayList<>(List.of(87, 92)));
var prices = new HashMap<String, Double>(); // var: types on the right
prices.put("Pen", 10.0);
var unclear = new ArrayList<>(); // ArrayList<Object>: avoid
unclear.add("anything");
unclear.add(3.14);
System.out.println(marks + " " + prices + " " + unclear);
}
} Bounded type parameters
<T extends Number>is an upper bound:Tmust beNumberor a subclass (Integer,Double,Long).- Inside the class or method you can then call the methods of the bound, such as
doubleValue(). extendsis used for both classes and interfaces in bounds:<T extends Comparable<T>>.- Multiple bounds use
&, with the class first:<T extends Number & Comparable<T>>. - Real life: a parking lot with a board "four-wheelers only". Cars, SUVs, and vans may enter; bicycles may not.
import java.util.List;
class Stats<T extends Number> { // only numeric types allowed
private final List<T> values;
Stats(List<T> values) {
this.values = values;
}
double average() {
double sum = 0;
for (T v : values) {
sum += v.doubleValue(); // allowed because T is a Number
}
return values.isEmpty() ? 0 : sum / values.size();
}
}
public class BoundedDemo {
static <T extends Comparable<T>> T max(List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
public static void main(String[] args) {
System.out.println(new Stats<>(List.of(80, 90, 100)).average()); // 90.0
System.out.println(new Stats<>(List.of(2.5, 3.5)).average()); // 3.0
// new Stats<>(List.of("a", "b")); // ERROR: String is not a Number
System.out.println(max(List.of(45, 99, 12))); // 99
System.out.println(max(List.of("mango", "apple", "kiwi"))); // mango
}
} Generics work only with reference types
- Type arguments must be classes, not primitives:
List<int>is a compile error. Use the wrapper class. - Autoboxing converts automatically:
list.add(5)stores anInteger, andint x = list.get(0)unboxes it. - Unboxing a
nullelement throwsNullPointerException. - For large numeric data, primitive streams (
IntStream) or arrays avoid boxing overhead.
| Primitive | Use in generics | Example |
|---|---|---|
int | Integer | List<Integer> marks |
double | Double | Map<String, Double> prices |
char | Character | Set<Character> vowels |
boolean | Boolean | Map<String, Boolean> flags |
long | Long | List<Long> ids |
Wildcards: ?, ? extends, ? super
?means "some unknown type". Wildcards are used in variable and parameter types, not when creating objects.List<? extends Number>: a list of Number or any subclass. You can readNumbervalues, but cannot add (exceptnull).List<? super Integer>: a list of Integer or any superclass. You can addIntegervalues, but reads returnObject.List<?>: any list. Read asObject, cannot add (exceptnull).- Real life: "? extends Fruit" is a fruit basket you can take fruit from, but you do not know which fruit fits back in. "? super Apple" is a bin that accepts apples, but you do not know what else is in it.
| Type | Accepts which lists? | Read as | Can add |
|---|---|---|---|
List<Integer> | Only List<Integer> | Integer | Integer |
List<? extends Number> | List<Number>, List<Integer>, List<Double> | Number | Nothing (only null) |
List<? super Integer> | List<Integer>, List<Number>, List<Object> | Object | Integer (or subclass) |
List<?> | Any list | Object | Nothing (only null) |
import java.util.ArrayList;
import java.util.List;
public class WildcardDemo {
static double total(List<? extends Number> nums) { // reads only
double sum = 0;
for (Number n : nums) {
sum += n.doubleValue();
}
return sum;
}
static void addRollNumbers(List<? super Integer> dest) { // writes only
for (int i = 1; i <= 3; i++) {
dest.add(i);
}
}
static void printAny(List<?> list) { // any list, read as Object
for (Object o : list) {
System.out.print(o + " ");
}
System.out.println();
}
public static void main(String[] args) {
System.out.println(total(List.of(1, 2, 3))); // 6.0 (List<Integer>)
System.out.println(total(List.of(1.5, 2.5))); // 4.0 (List<Double>)
List<Number> numbers = new ArrayList<>();
List<Object> objects = new ArrayList<>();
addRollNumbers(numbers);
addRollNumbers(objects);
printAny(numbers); // 1 2 3
printAny(List.of("a", "b")); // a b
}
} Generics and inheritance: List of Integer is not a List of Number
Integeris a subclass ofNumber, butList<Integer>is NOT a subtype ofList<Number>. Generic types are invariant.- Reason: if it were allowed, someone could add a
Doubleinto your list of integers through theList<Number>reference. - Arrays are covariant (
Integer[]is aNumber[]), which is why arrays can fail at runtime withArrayStoreException. Generics catch the same mistake at compile time. - Use
List<? extends Number>when you need a parameter that accepts lists of any numeric type.
import java.util.ArrayList;
import java.util.List;
public class InvarianceDemo {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>(List.of(1, 2));
// List<Number> nums = ints; // compile error: incompatible types
List<? extends Number> ok = ints; // OK: read-only view as Number
System.out.println(ok.get(0));
Integer[] intArray = { 1, 2 };
Object[] objArray = intArray; // arrays are covariant: compiles
try {
objArray[0] = "oops"; // fails at runtime
} catch (ArrayStoreException e) {
System.out.println("Runtime: " + e.getClass().getSimpleName());
}
}
} Differences between bounded type parameters and wildcards
| Point | Bounded type parameter <T extends X> | Wildcard ? extends X / ? super X |
|---|---|---|
| Where declared | On a class, interface, or method | In a variable or parameter type |
| Has a name? | Yes, T, so you can reuse it | No, it is anonymous |
Lower bound (super) | Not allowed | Allowed: ? super Integer |
| Multiple bounds | Allowed: T extends Number & Comparable<T> | Not allowed |
| Relate two parameters | Yes: <T> void copy(List<T> a, List<T> b) | No |
| Typical use | Generic classes and methods that return or store T | Flexible method parameters that only read or only write |
Advanced — Generics
PECS: Producer Extends, Consumer Super
- If a parameter produces values you read, use
? extends T. If it consumes values you write, use? super T. - If it does both, use plain
Twith no wildcard. - Real life: a water tank produces water (you only take from it), and a bucket consumes water (you only pour into it).
- The JDK uses PECS everywhere:
Collections.copy(List<? super T> dest, List<? extends T> src)andCollections.max(Collection<? extends T>, Comparator<? super T>).
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class PecsDemo {
// src produces T (extends), dest consumes T (super)
static <T> void copy(List<? extends T> src, List<? super T> dest) {
for (T item : src) {
dest.add(item);
}
}
static <T> T best(List<? extends T> items, Comparator<? super T> cmp) {
T best = items.get(0);
for (T item : items) {
if (cmp.compare(item, best) > 0) best = item;
}
return best;
}
public static void main(String[] args) {
List<Integer> tank = List.of(10, 20, 30); // producer
List<Number> bucket = new ArrayList<>(); // consumer
copy(tank, bucket);
System.out.println(bucket); // [10, 20, 30]
Comparator<Number> byValue = Comparator.comparingDouble(Number::doubleValue);
System.out.println(best(tank, byValue)); // 30: a Number comparator works for Integers
}
} Type erasure: what the compiler does
- Generics exist only at compile time. The compiler checks types, then erases type parameters and inserts casts.
- Unbounded
TbecomesObject; boundedT extends NumberbecomesNumber. - At runtime
List<String>andList<Integer>are the same class,ArrayList. - The compiler may add bridge methods so overriding still works after erasure.
- Erasure kept Java 5 bytecode compatible with older code and libraries.
| You write | After erasure (bytecode view) |
|---|---|
class Box<T> { T value; } | class Box { Object value; } |
class Stats<T extends Number> { T n; } | class Stats { Number n; } |
String s = box.get(); | String s = (String) box.get(); |
List<String> list | List list |
import java.util.ArrayList;
import java.util.List;
public class ErasureDemo {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
List<Integer> marks = new ArrayList<>();
System.out.println(names.getClass() == marks.getClass()); // true
System.out.println(names.getClass().getName()); // java.util.ArrayList
Object o = names;
// if (o instanceof List<String>) { } // ERROR: String is erased, cannot be checked at runtime
System.out.println(o instanceof List<?>); // true: unbounded wildcard is allowed
}
} Restrictions on generics
| Not allowed | Why | Workaround |
|---|---|---|
new T() | The type of T is erased at runtime | Pass a Supplier<T> or Class<T> |
new T[10] | Array creation needs the runtime type | (T[]) new Object[10] inside the class, or Array.newInstance(cls, n) |
List<int> | Type arguments must be reference types | Use List<Integer> |
static T field; | Static members are shared by all Box<X> types | Make the static member generic itself, or non-static |
obj instanceof List<String> | Type arguments do not exist at runtime | obj instanceof List<?> |
class MyEx<T> extends Exception | catch cannot tell erased types apart | Store the data in a field instead |
Overloads f(List<String>) and f(List<Integer>) | Same signature after erasure | Use different method names |
new List<String>[5] | Generic array creation is unsafe | Use List<List<String>> |
Creating objects of T with Supplier and Class tokens
- Because
new T()is impossible, pass a factory: aSupplier<T>(likeStudent::new) or aClass<T>token. Class<T>also lets you check and cast at runtime withtype.isInstance(obj)andtype.cast(obj).
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
class Ticket {
private static int next = 1;
final int no = next++;
@Override public String toString() { return "Ticket#" + no; }
}
public class FactoryDemo {
static <T> List<T> createMany(Supplier<T> factory, int count) {
List<T> list = new ArrayList<>();
for (int i = 0; i < count; i++) {
list.add(factory.get()); // creates a new T each time
}
return list;
}
static <T> List<T> filterByType(List<?> items, Class<T> type) {
List<T> result = new ArrayList<>();
for (Object o : items) {
if (type.isInstance(o)) {
result.add(type.cast(o)); // safe cast using the token
}
}
return result;
}
public static void main(String[] args) {
System.out.println(createMany(Ticket::new, 3)); // [Ticket#1, Ticket#2, Ticket#3]
List<Object> mixed = List.of("Asha", 42, "Ravi", 3.5);
System.out.println(filterByType(mixed, String.class)); // [Asha, Ravi]
}
} Recursive bounds: T extends Comparable of super T
<T extends Comparable<? super T>>means T can be compared with itself or with a supertype. This is the signature ofCollections.maxandCollections.sort.- The
? super Tpart lets a subclass reuse the comparison defined in its parent class.
import java.util.List;
class Employee implements Comparable<Employee> {
final String name;
final double salary;
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
@Override
public int compareTo(Employee other) {
return Double.compare(salary, other.salary);
}
@Override
public String toString() { return name + "(" + salary + ")"; }
}
class Manager extends Employee { // Comparable<Employee>, not Comparable<Manager>
Manager(String name, double salary) { super(name, salary); }
}
public class RecursiveBound {
static <T extends Comparable<? super T>> T max(List<? extends T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) best = item;
}
return best;
}
public static void main(String[] args) {
List<Manager> managers = List.of(new Manager("Asha", 150000), new Manager("Ravi", 180000));
System.out.println(max(managers)); // Ravi(180000.0): works thanks to ? super T
}
} Raw types, unchecked warnings, and heap pollution
- A raw type (
Listwith no type argument) switches off generic checking. Mixing raw and generic code produces unchecked warnings. - Heap pollution: a variable of type
List<String>ends up pointing to a list that holds other types. The failure appears later, far from the cause. - Generic varargs (
T... items) create a generic array and can cause heap pollution. Mark safe methods with@SafeVarargs(only on static, final, or private methods). - Treat unchecked warnings as bugs. Use
@SuppressWarnings("unchecked")only on the smallest scope, with a comment explaining why it is safe.
import java.util.ArrayList;
import java.util.List;
public class HeapPollution {
@SafeVarargs
static <T> List<T> listOf(T... items) { // safe: only reads the array
List<T> list = new ArrayList<>();
for (T item : items) list.add(item);
return list;
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
List<String> names = new ArrayList<>();
List raw = names; // raw type: checks switched off
raw.add(99); // heap pollution: an Integer inside List<String>
try {
String s = names.get(0); // ClassCastException appears HERE, far from the cause
System.out.println(s);
} catch (ClassCastException e) {
System.out.println("Polluted list: " + e.getClass().getSimpleName());
}
System.out.println(listOf("Java", "Generics"));
}
} Wildcard capture and helper methods
- You cannot add to a
List<?>, so a method likeswap(List<?> list, int i, int j)fails to compile if written directly. - Fix: call a private generic helper
<T>that "captures" the unknown type and gives it a name. - If the compiler mentions
capture#1 of ?, this pattern is usually the answer.
import java.util.ArrayList;
import java.util.List;
public class CaptureDemo {
static void swap(List<?> list, int i, int j) {
swapHelper(list, i, j); // captures ? as T
}
private static <T> void swapHelper(List<T> list, int i, int j) {
T tmp = list.get(i);
list.set(i, list.get(j));
list.set(j, tmp);
}
public static void main(String[] args) {
List<String> queue = new ArrayList<>(List.of("Asha", "Ravi", "Kiran"));
swap(queue, 0, 2);
System.out.println(queue); // [Kiran, Ravi, Asha]
}
} Generics in the JDK
| Generic type | Type parameters | Meaning |
|---|---|---|
List<E>, Set<E>, Queue<E> | E element | Collections of one element type |
Map<K, V> | K key, V value | Key to value lookup |
Optional<T> | T value | A value that may be absent |
Comparable<T>, Comparator<T> | T compared type | Ordering objects |
Function<T, R> | T input, R result | Converts T to R |
Predicate<T>, Consumer<T>, Supplier<T> | T | Test, accept, or supply a T |
Stream<T> | T element | Pipeline of T values |
Class<T> | T the represented type | String.class is a Class<String> |
CompletableFuture<T> | T future result | An async result of type T |
Tricky Interview Points
Q1) What are generics in Java?
Answer A feature (Java 5) that lets classes, interfaces, and methods take type parameters, giving compile-time type safety and removing casts, while one implementation works for many types.
Q2) Give a real-life example of generics.
Answer A labelled storage box: one box design, but a box labelled Books accepts only books. In Java, Box<Book> accepts only Book objects, and the compiler rejects anything else.
Q3) What are the advantages of generics?
Answer Type safety at compile time, no explicit casts, reusable code and algorithms, and clearer APIs that document their types.
Q4) What is a generic class?
Answer A class declared with type parameters, such as class Box<T>. The type is supplied when creating objects, for example Box<String>.
Q5) What is a generic method?
Answer A method that declares its own type parameters before the return type, such as static <T> T firstOf(List<T> list). It can be in a generic or non-generic class.
Q6) What is the diamond operator?
Answer The empty <> in new ArrayList<>(). The compiler infers the type arguments from the context. Added in Java 7.
Q7) Why can we not use primitives as type arguments?
Answer Generics work with reference types because of erasure to Object or a bound. Use wrapper classes such as Integer; autoboxing converts automatically.
Q8) What is a bounded type parameter?
Answer A type parameter restricted with extends, such as <T extends Number>, so only Number or its subclasses are allowed and Number methods can be called on T.
Q9) Can a type parameter have multiple bounds?
Answer Yes, with &, for example <T extends Number & Comparable<T>>. A class bound must come first, followed by interfaces.
Q10) What is a wildcard in generics?
Answer The ? symbol meaning an unknown type. It can be unbounded (?), upper bounded (? extends T), or lower bounded (? super T).
Q11) What is the difference between ? extends and ? super?
Answer ? extends T accepts T or its subtypes and is good for reading. ? super T accepts T or its supertypes and is good for writing T values.
Q12) What is PECS?
Answer Producer Extends, Consumer Super. Use ? extends T for parameters you read from, ? super T for parameters you write to, and plain T when you do both.
Q13) Is List<Integer> a subtype of List<Number>?
Answer No. Generic types are invariant. Otherwise a Double could be added to a list of Integers. Use List<? extends Number> to accept both.
Q14) What is the difference between List<?> and List<Object>?
Answer List<Object> holds any objects and you can add to it, but only a List<Object> can be assigned to it. List<?> accepts a list of any type, but you can only add null.
Q15) What is type erasure?
Answer The compiler removes type parameters after checking, replacing them with Object or their bound and inserting casts. At runtime List<String> and List<Integer> are the same class.
Q16) Why can we not create new T() or new T[]?
Answer Because T is erased, the JVM does not know the real type at runtime. Pass a Supplier<T> or Class<T> instead.
Q17) Can we overload methods that differ only in generic parameter types?
Answer No. f(List<String>) and f(List<Integer>) have the same erasure, so the compiler reports a name clash.
Q18) What is a raw type?
Answer A generic type used without type arguments, such as List. It exists for backward compatibility and disables type checking, so it should not be used in new code.
Q19) What is heap pollution?
Answer When a variable of a parameterized type refers to an object that is not of that type, usually through raw types or unchecked casts, causing a ClassCastException later.
Q20) What does @SafeVarargs do?
Answer It tells the compiler that a generic varargs method does not perform unsafe operations on its array, suppressing the warnings. It is allowed on static, final, and private methods and constructors.
Simple Programs
Generic Stack with push, pop, and peek
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
class Stack<T> {
private final List<T> items = new ArrayList<>();
void push(T item) { items.add(item); }
T pop() {
if (items.isEmpty()) throw new NoSuchElementException("stack is empty");
return items.remove(items.size() - 1);
}
T peek() {
if (items.isEmpty()) throw new NoSuchElementException("stack is empty");
return items.get(items.size() - 1);
}
boolean isEmpty() { return items.isEmpty(); }
}
public class StackDemo {
public static void main(String[] args) {
Stack<String> plates = new Stack<>(); // like a stack of plates
plates.push("Plate 1");
plates.push("Plate 2");
plates.push("Plate 3");
System.out.println(plates.peek()); // Plate 3
while (!plates.isEmpty()) {
System.out.println("Washing " + plates.pop());
}
Stack<Integer> undo = new Stack<>(); // same class, different type
undo.push(10);
undo.push(20);
System.out.println("Undo to " + undo.pop()); // 20
}
} Generic method: count frequencies of any type
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class FrequencyCounter {
static <T> Map<T, Integer> countAll(List<T> items) {
Map<T, Integer> counts = new LinkedHashMap<>();
for (T item : items) {
counts.merge(item, 1, Integer::sum);
}
return counts;
}
public static void main(String[] args) {
System.out.println(countAll(List.of("tea", "coffee", "tea", "juice", "tea")));
// {tea=3, coffee=1, juice=1}
System.out.println(countAll(List.of(5, 3, 5, 5, 3)));
// {5=3, 3=2}
System.out.println(countAll(List.of('a', 'b', 'a')));
// {a=2, b=1}
}
} Bounded generic: marks statistics
import java.util.List;
class MarksStats<N extends Number> {
private final List<N> marks;
MarksStats(List<N> marks) {
this.marks = marks;
}
double average() {
return marks.stream().mapToDouble(Number::doubleValue).average().orElse(0);
}
double highest() {
return marks.stream().mapToDouble(Number::doubleValue).max().orElse(0);
}
long passed(double passMark) {
return marks.stream().filter(m -> m.doubleValue() >= passMark).count();
}
}
public class MarksDemo {
public static void main(String[] args) {
MarksStats<Integer> maths = new MarksStats<>(List.of(78, 92, 35, 64, 88));
System.out.printf("Average %.1f, highest %.0f, passed %d%n",
maths.average(), maths.highest(), maths.passed(40));
// Average 71.4, highest 92, passed 4
MarksStats<Double> lab = new MarksStats<>(List.of(8.5, 9.0, 7.25));
System.out.printf("Lab average %.2f%n", lab.average()); // 8.25
}
} Generic Result type: success or failure
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; }
}
public class ResultDemo {
static Result<Integer> parseAge(String text) {
try {
int age = Integer.parseInt(text);
return age >= 0 ? Result.ok(age) : Result.fail("age cannot be negative");
} catch (NumberFormatException e) {
return Result.fail("'" + text + "' is not a number");
}
}
public static void main(String[] args) {
for (String input : new String[] { "25", "-3", "abc" }) {
Result<Integer> r = parseAge(input);
System.out.println(input + " -> " + (r.isOk() ? "age " + r.get() : "error: " + r.error()));
}
}
} Wildcards: total bill from any numeric list
import java.util.ArrayList;
import java.util.List;
public class BillCalculator {
static double total(List<? extends Number> amounts) { // producer: read only
double sum = 0;
for (Number n : amounts) sum += n.doubleValue();
return sum;
}
static void addDiscounts(List<? super Integer> discounts) { // consumer: write only
discounts.add(50);
discounts.add(100);
}
public static void main(String[] args) {
List<Integer> groceries = List.of(120, 340, 75);
List<Double> medicines = List.of(99.5, 249.75);
System.out.println("Groceries: " + total(groceries)); // 535.0
System.out.println("Medicines: " + total(medicines)); // 349.25
List<Number> discounts = new ArrayList<>();
addDiscounts(discounts);
System.out.println("Discounts: " + total(discounts)); // 150.0
}
} Generic cache with a size limit
import java.util.LinkedHashMap;
import java.util.Map;
class LruCache<K, V> extends LinkedHashMap<K, V> {
private final int capacity;
LruCache(int capacity) {
super(16, 0.75f, true); // access order: recently used last
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity; // remove the least recently used entry
}
}
public class CacheDemo {
public static void main(String[] args) {
LruCache<String, Double> prices = new LruCache<>(2);
prices.put("Gold", 7245.0);
prices.put("Silver", 92.5);
prices.get("Gold"); // Gold becomes most recently used
prices.put("Platinum", 3150.0); // Silver is removed
System.out.println(prices); // {Gold=7245.0, Platinum=3150.0}
}
} Generic utility: find max and min with Comparable
import java.util.List;
public class MinMax {
static <T extends Comparable<? super T>> T max(List<T> list) {
T best = list.get(0);
for (T t : list) if (t.compareTo(best) > 0) best = t;
return best;
}
static <T extends Comparable<? super T>> T min(List<T> list) {
T best = list.get(0);
for (T t : list) if (t.compareTo(best) < 0) best = t;
return best;
}
public static void main(String[] args) {
List<Integer> temps = List.of(31, 38, 27, 35);
List<String> names = List.of("Ravi", "Asha", "Kiran");
System.out.println("Hottest " + max(temps) + ", coolest " + min(temps)); // 38, 27
System.out.println("First " + min(names) + ", last " + max(names)); // Asha, Ravi
}
} Problem Solving Tricks
- Read
List<String>as "list of String" andBox<T>as "box of T". - Use the diamond:
new ArrayList<>(). Withvar, put the type on the right. - No primitives in angle brackets:
List<Integer>, notList<int>. - PECS: Producer Extends, Consumer Super. Reading = extends, writing = super, both = plain T.
List<Integer>is not aList<Number>; useList<? extends Number>to accept both.- Erasure means no
new T(), nonew T[], and noinstanceof List<String>. Pass aSupplier<T>orClass<T>instead. - If the error mentions "capture#1 of ?", write a private generic helper method.
- Never ignore raw type or unchecked warnings; they disable generic safety.
- Bounds use
extendsfor both classes and interfaces; multiple bounds use&with the class first. - Return
List<T>orOptional<T>, not raw types orObject.
Practice Programs List
- Write
class Box<T>withput,get, andisEmpty, and use it withString,Integer, and aBookclass. - Write
class Pair<K, V>with getters andtoString, and store roll number and name pairs. - Write a generic method
printAll(T[] items)and call it withInteger[]andString[]. - Write a generic interface
Repository<T, ID>and an in-memory implementation using aHashMap. - Write
class Stats<T extends Number>withaverage()and show thatStats<String>does not compile. - Write
static <T extends Comparable<T>> T max(List<T> list)and test it with numbers and strings. - Write
total(List<? extends Number>)and call it withList<Integer>andList<Double>. - Write
fill(List<? super Integer>)and call it withList<Number>andList<Object>. - Demonstrate that
List<Integer>cannot be assigned toList<Number>, and thatInteger[]can be assigned toObject[]but fails at runtime. - Implement
copywith PECS, then swap the wildcards and read the compiler errors. - Print
getClass()for aList<String>and aList<Integer>to see type erasure. - Write
createMany(Supplier<T>, int)that creates several objects withoutnew T(). - Write a generic
Stack<T>and use it for plates (String) and undo steps (Integer). - Write
countAll(List<T>)that returns aMap<T, Integer>of frequencies.