×

java · level 3 · unit 1 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A tells Java what your type can do.

Inside <T>, Java knows nothing about T, so it only lets you call methods every object has, like equals. To find the biggest item you need to compare them, and plain T has no compareTo. Writing x.compareTo(y) gives cannot find symbol.

A bound fixes this. means any type that can compare itself with its own kind. String, Integer and Double all implement Comparable, so they are allowed in, and inside the method compareTo is ready to use.

a.compareTo(b) answers with a number: negative when a comes first, zero when they match, positive when a comes after. Check the sign, never the exact value.

import java.util.List;
public class Main {
    static <T extends Comparable<T>> T biggest(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(biggest(List.of(18, 42, 7)));
        System.out.println(biggest(List.of("kiwi", "apple", "mango")));
        System.out.println(biggest(List.of(2.5, 9.75, 4.0)));
    }
}

Here extends means "is or implements", for classes and interfaces alike.