Skip to main content

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.

L1

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

BenefitMeaningExample
Type safetyWrong types are rejected at compile timeList<String> cannot add(42)
No castingThe compiler inserts casts for youString s = names.get(0);
Code reuseOne class or method works for many typesBox<Book>, Box<Toy>, Box<Integer>
Readable APIsTypes document what goes in and comes outMap<String, List<Order>>
Early bug detectionErrors appear while compiling, not in productionNo surprise ClassCastException
Generic algorithmsSort, search, and copy any comparable typeCollections.sort(List<T>)

Differences between code without generics and with generics

PointWithout generics (raw types)With generics
DeclarationList list = new ArrayList();List<String> list = new ArrayList<>();
Type checkingNone: any object can be addedCompile-time: only the declared type
Reading valuesNeeds an explicit castNo cast needed
When errors appearAt runtime (ClassCastException)At compile time
Compiler warningsUnchecked / raw type warningsNone
ReadabilityUnclear what the list holdsType is visible in the declaration
Use todayOnly for legacy codeAlways 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.
LetterStands forUsed in
TTypeBox<T>, Optional<T>
EElementList<E>, Set<E>
KKeyMap<K, V>
VValueMap<K, V>
NNumberStats<N extends Number>
RResult / return typeFunction<T, R>
S, U, VSecond, third, fourth typesTriple<T, U, V>

Generic class

  • Add the type parameter after the class name: class Box<T>. Use T like 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 T from 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>();. Writing var list = new ArrayList<>(); gives ArrayList<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: T must be Number or a subclass (Integer, Double, Long).
  • Inside the class or method you can then call the methods of the bound, such as doubleValue().
  • extends is 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 an Integer, and int x = list.get(0) unboxes it.
  • Unboxing a null element throws NullPointerException.
  • For large numeric data, primitive streams (IntStream) or arrays avoid boxing overhead.
PrimitiveUse in genericsExample
intIntegerList<Integer> marks
doubleDoubleMap<String, Double> prices
charCharacterSet<Character> vowels
booleanBooleanMap<String, Boolean> flags
longLongList<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 read Number values, but cannot add (except null).
  • List<? super Integer>: a list of Integer or any superclass. You can add Integer values, but reads return Object.
  • List<?>: any list. Read as Object, cannot add (except null).
  • 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.
TypeAccepts which lists?Read asCan add
List<Integer>Only List<Integer>IntegerInteger
List<? extends Number>List<Number>, List<Integer>, List<Double>NumberNothing (only null)
List<? super Integer>List<Integer>, List<Number>, List<Object>ObjectInteger (or subclass)
List<?>Any listObjectNothing (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

  • Integer is a subclass of Number, but List<Integer> is NOT a subtype of List<Number>. Generic types are invariant.
  • Reason: if it were allowed, someone could add a Double into your list of integers through the List<Number> reference.
  • Arrays are covariant (Integer[] is a Number[]), which is why arrays can fail at runtime with ArrayStoreException. 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

PointBounded type parameter <T extends X>Wildcard ? extends X / ? super X
Where declaredOn a class, interface, or methodIn a variable or parameter type
Has a name?Yes, T, so you can reuse itNo, it is anonymous
Lower bound (super)Not allowedAllowed: ? super Integer
Multiple boundsAllowed: T extends Number & Comparable<T>Not allowed
Relate two parametersYes: <T> void copy(List<T> a, List<T> b)No
Typical useGeneric classes and methods that return or store TFlexible method parameters that only read or only write
L2

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 T with 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) and Collections.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 T becomes Object; bounded T extends Number becomes Number.
  • At runtime List<String> and List<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 writeAfter 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> listList 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 allowedWhyWorkaround
new T()The type of T is erased at runtimePass 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 typesUse List<Integer>
static T field;Static members are shared by all Box<X> typesMake the static member generic itself, or non-static
obj instanceof List<String>Type arguments do not exist at runtimeobj instanceof List<?>
class MyEx<T> extends Exceptioncatch cannot tell erased types apartStore the data in a field instead
Overloads f(List<String>) and f(List<Integer>)Same signature after erasureUse different method names
new List<String>[5]Generic array creation is unsafeUse List<List<String>>

Creating objects of T with Supplier and Class tokens

  • Because new T() is impossible, pass a factory: a Supplier<T> (like Student::new) or a Class<T> token.
  • Class<T> also lets you check and cast at runtime with type.isInstance(obj) and type.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 of Collections.max and Collections.sort.
  • The ? super T part 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 (List with 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 like swap(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 typeType parametersMeaning
List<E>, Set<E>, Queue<E>E elementCollections of one element type
Map<K, V>K key, V valueKey to value lookup
Optional<T>T valueA value that may be absent
Comparable<T>, Comparator<T>T compared typeOrdering objects
Function<T, R>T input, R resultConverts T to R
Predicate<T>, Consumer<T>, Supplier<T>TTest, accept, or supply a T
Stream<T>T elementPipeline of T values
Class<T>T the represented typeString.class is a Class<String>
CompletableFuture<T>T future resultAn async result of type T
L3

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.

L4

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
    }
}
L5

Problem Solving Tricks

  • Read List<String> as "list of String" and Box<T> as "box of T".
  • Use the diamond: new ArrayList<>(). With var, put the type on the right.
  • No primitives in angle brackets: List<Integer>, not List<int>.
  • PECS: Producer Extends, Consumer Super. Reading = extends, writing = super, both = plain T.
  • List<Integer> is not a List<Number>; use List<? extends Number> to accept both.
  • Erasure means no new T(), no new T[], and no instanceof List<String>. Pass a Supplier<T> or Class<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 extends for both classes and interfaces; multiple bounds use & with the class first.
  • Return List<T> or Optional<T>, not raw types or Object.
L6

Practice Programs List

  1. Write class Box<T> with put, get, and isEmpty, and use it with String, Integer, and a Book class.
  2. Write class Pair<K, V> with getters and toString, and store roll number and name pairs.
  3. Write a generic method printAll(T[] items) and call it with Integer[] and String[].
  4. Write a generic interface Repository<T, ID> and an in-memory implementation using a HashMap.
  5. Write class Stats<T extends Number> with average() and show that Stats<String> does not compile.
  6. Write static <T extends Comparable<T>> T max(List<T> list) and test it with numbers and strings.
  7. Write total(List<? extends Number>) and call it with List<Integer> and List<Double>.
  8. Write fill(List<? super Integer>) and call it with List<Number> and List<Object>.
  9. Demonstrate that List<Integer> cannot be assigned to List<Number>, and that Integer[] can be assigned to Object[] but fails at runtime.
  10. Implement copy with PECS, then swap the wildcards and read the compiler errors.
  11. Print getClass() for a List<String> and a List<Integer> to see type erasure.
  12. Write createMany(Supplier<T>, int) that creates several objects without new T().
  13. Write a generic Stack<T> and use it for plates (String) and undo steps (Integer).
  14. Write countAll(List<T>) that returns a Map<T, Integer> of frequencies.