Core Java

core20GenericsDemo

Path
pkg1core/core20GenericsDemo.java
Package
pkg1core
Study order
21
Run
Single-file source launch
Command
java pkg1core/core20GenericsDemo.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core20GenericsDemo.java
1package pkg1core;2 3/*4 * core20GenericsDemo.java5 * -----------------6 * Generic classes/methods, bounded type parameters, wildcards (PECS).7 *8 * EXPLANATION:9 *  - Generics give compile-time type safety and remove casts.10 *  - Type erasure: generic type info is removed at runtime.11 *  - PECS: Producer Extends, Consumer Super.12 *      * `? extends T` to READ (produce) Ts.13 *      * `? super T`   to WRITE (consume) Ts.14 */15import java.util.*;16 17public class core20GenericsDemo {18 19    // Generic class (a simple immutable pair)20    static class Pair<A, B> {21        final A first; final B second;22        Pair(A a, B b){ first = a; second = b; }23        public String toString(){ return "(" + first + ", " + second + ")"; }24    }25 26    // Generic method with a bounded type parameter27    static <T extends Comparable<T>> T max(List<T> items) {28        T best = items.get(0);29        for (T x : items) if (x.compareTo(best) > 0) best = x;30        return best;31    }32 33    // PRODUCER: read from a source of "? extends Number"34    static double sum(List<? extends Number> nums) {35        double s = 0;36        for (Number n : nums) s += n.doubleValue();37        return s;38    }39 40    // CONSUMER: write Integers into "? super Integer"41    static void addInts(List<? super Integer> sink, int count) {42        for (int i = 1; i <= count; i++) sink.add(i);43    }44 45    public static void main(String[] args) {46        Pair<String, Integer> p = new Pair<>("age", 30);47        System.out.println("Pair: " + p);48 49        System.out.println("max([3,9,5,7]) = " + max(List.of(3, 9, 5, 7)));50        System.out.println("max(words)     = " + max(List.of("apple", "pear", "kiwi")));51 52        System.out.println("sum(ints)    = " + sum(List.of(1, 2, 3)));53        System.out.println("sum(doubles) = " + sum(List.of(1.5, 2.5)));54 55        List<Number> sink = new ArrayList<>();56        addInts(sink, 3);57        System.out.println("consumer sink: " + sink);58    }59}