FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
Dobbs M-Dev
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
February 01, 2000

GJ A Generic Java

(Page 4 of 7)
Feb00: GJ A Generic Java


interface Comparable {
  public int compareTo (Object that);
}
class Byte implements Comparable {
  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;
  }
  // bridge
  public int compareTo (Object that) {
    return this.compareTo((Byte)that);
  }
}
class Lists {
  public static Comparable max (List xs) {
    Iterator xi = xs.iterator();
    Comparable w = (Comparable)xi.next();
    while (xi.hasNext()) {
      Comparable x = (Comparable)xi.next();
      if (w.compareTo(x) < 0) w = x;
    }
    return w;
  }
}
class Test {
  public static void main (String[] args) {

    // byte list
    List xs = new LinkedList();
    xs.add(new Byte(0)); xs.add(new Byte(1));
    Byte x = (Byte)Lists.max(xs);

    // boolean list
    List ys = new LinkedList();
    ys.add(new Boolean(false)); ys.add(new Boolean(true));
    Boolean y = (Boolean)Lists.max(ys);  // run-time exception
  }
}

Example 3: Declarations for the Comparable interface and the Byte class that implements this interface.

Previous Page | 1 | 2 | 3 | 4 | 5 | 6 | 7 Next Page
RELATED ARTICLES
No Related Articles
TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK