Class Counter

  • All Implemented Interfaces:
    Comparable<Counter>

    public class Counter
    extends Object
    implements Comparable<Counter>
    The Counter class is a mutable data type to encapsulate a counter.

    For additional documentation, see Section 1.2 of Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.

    Author:
    Robert Sedgewick, Kevin Wayne
    • Constructor Detail

      • Counter

        public Counter​(String id)
        Initializes a new counter starting at 0, with the given id.
        Parameters:
        id - the name of the counter
    • Method Detail

      • increment

        public void increment()
        Increments the counter by 1.
      • tally

        public int tally()
        Returns the current value of this counter.
        Returns:
        the current value of this counter
      • toString

        public String toString()
        Returns a string representation of this counter.
        Overrides:
        toString in class Object
        Returns:
        a string representation of this counter
      • compareTo

        public int compareTo​(Counter that)
        Compares this counter to the specified counter.
        Specified by:
        compareTo in interface Comparable<Counter>
        Parameters:
        that - the other counter
        Returns:
        0 if the value of this counter equals the value of that counter; a negative integer if the value of this counter is less than the value of that counter; and a positive integer if the value of this counter is greater than the value of that counter
      • main

        public static void main​(String[] args)
        Reads two command-line integers n and trials; creates n counters; increments trials counters at random; and prints results.
        Parameters:
        args - the command-line arguments