interface Comparable<A> {
  public int compareTo (A that);
}
class Byte implements Comparable<Byte> {
  private byte value;
  public Byte (byte value) { this.value = value; }
  public byte byteValue () { return value; }
  public int compareTo (Byte that) {
    return this.value - that.value;
  }
}
class Lists {
  public static <A implements Comparable<A>> A max (List<A> xs) {
    Iterator<A> xi = xs.iterator();
    A w = xi.next();
    while (xi.hasNext()) {
      A x = xi.next();
      if (w.compareTo(x) < 0) w = x;
    }
    return w;
  }
}
class Test {
  public static void main (String[] args) {

    // byte collection
    LinkedList<Byte> xs = new LinkedList<Byte>();
    xs.add(new Byte(0)); xs.add(new Byte(1));
    Byte x = Collections.max(xs);

    // boolean collection
    LinkedList<Boolean> ys = new LinkedList<Boolean>();
    ys.add(new Boolean(false)); ys.add(new Boolean(true));
    Boolean y = Collections.max(ys);  // compile-time error
  }
}

Example 4: Code rewritten in GJ.

Back to Article