Java generics and bounded types

Generics let a class or method have type parameters. Box<T> can hold any one type, but each Box<String> or Box<Integer> is checked by the compiler, so no casts are needed when reading the value. Without generics a container of Object would need casts and could fail at run time.

Java
import java.util.*;

class Main {
  static class Box<T> {
    private final T value;

    Box(T value) {
      this.value = value;
    }

    T get() {
      return value;
    }
  }

  static <T extends Comparable<T>> T largest(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) {
    Box<String> name = new Box<>("Ada");
    Box<Integer> age = new Box<>(36);
    String upper = name.get().toUpperCase();
    int next = age.get() + 1;
    System.out.println(upper + " " + next);

    System.out.println(largest(Arrays.asList(3, 9, 4)));
    System.out.println(largest(Arrays.asList("pear", "apple", "zebra", "mango")));
  }
}
Read the full lesson