Codiqo

Learn Java · lesson 60 of 61 · about 10 minutes

Generics

Write classes and methods that work for any type, with the compiler checking the types for you.

What you'll learn

  • Write a generic class with <T>
  • Write a generic method
  • Limit a type parameter with extends

The manager's summary

Before the manager goes home, the desk prints a short summary: just the first few items of each list, and how many more there are. The manager types how many to show, like 2, and gets Lost property: UMBRELLA, PHONE and 1 more, Seats: PREMIUM, STANDARD and 2 more and Shift hours: 8, 6 and 2 more. An empty list is none. The lost property is a list of Strings, the seats a list of SeatKinds and the hours a list of Integers, but one generic method can preview all three.

You've been using generics all along

ArrayList<String> and HashMap<String, Integer> are generic classes: the type in angle brackets is filled in when you use them, and the compiler makes sure only that type goes in.

You can write your own. class Box<T> makes T a type parameter, a stand-in for whatever type each Box is made with: Box<Integer>, Box<String>.

A generic Pair

public class Main {
    static class Pair<A, B> {
        private final A first;
        private final B second;

        Pair(A first, B second) {
            this.first = first;
            this.second = second;
        }

        A first() { return first; }
        B second() { return second; }

        Pair<B, A> swapped() {
            return new Pair<>(second, first);
        }
    }

    public static void main(String[] args) {
        Pair<String, Integer> p = new Pair<>("lives", 3);
        Pair<Integer, String> q = p.swapped();
        System.out.println(p.first() + " " + p.second() + " / " + q.first() + " " + q.second());
    }
}

Output

lives 3 / 3 lives

Generic methods and bounds

A method can have its own type parameter, written before the return type: static <T> T last(List<T> list). To compare items, say T must be comparable: <T extends Comparable<T>>. Then the method can call compareTo on them.

Biggest of any comparable type

import java.util.List;

public class Main {
    static <T extends Comparable<T>> T biggest(List<T> items) {
        T best = items.get(0);
        for (T x : items) {
            if (x.compareTo(best) > 0) best = x;
        }
        return best;
    }

    public static void main(String[] args) {
        System.out.println(biggest(List.of(3, 9, 4)));
        System.out.println(biggest(List.of("kiwi", "pear", "fig")));
    }
}

Output

9
pear

One preview for every list

static <T> String preview(List<T> items, int shown) declares T just for this method, so the compiler fills it in at each call: String for lostItems, SeatKind for seatsBooked and Integer for the shift hours. The method never needs to know which: it only turns each item into text with String.valueOf, which works for any object. The hours come from shifts.stream().map(Shift::hours).toList(), a List<Integer>.

Tip

Generics only work with object types. Use Integer, Double and Character instead of int, double and char; Java converts between them automatically.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.