Counter.java


Below is the syntax highlighted version of Counter.java from §3.6 Case Study: Purple America.


/*************************************************************************
 *  Compilation:  javac Counter.java
 *  Execution:    java Counter
 *
 *  Make it Comparable
 *
 *************************************************************************/

public final class Counter implements Comparable<Counter> {

    private final String name;      // the name of the counter
    private int count;              // the count

    // initialize the counter of given name to 0
    public Counter(String name) {
        this.name = name;
    }

    // increment the counter by 1
    public void hit() { count++; }

    // return a string representation of this counter
    public String toString() {
        return count + " " + name;
    }

    // implement the Comparable interface
    public int compareTo(Counter x) {
        if (this.count < x.count) return -1;
        if (this.count > x.count) return +1;
        return 0;
    }

}


Copyright © 2007, Robert Sedgewick and Kevin Wayne.
Last updated: Tue Sep 29 16:17:41 EDT 2009.