import java.util.*; /** A Comparator class that keeps track of the number of times that its compare method is invoked. The corresponding comparison counter can be queried and reset to 0. */ // The default constructor is adequate for this class. public class CountingComparator implements Comparator { int counter = 0; // the comparison counter /** Compares two objects according to the Comparator contract. @param o1 the first object @param o2 the second object @return an integer which is negative if the first object is smaller positive if the first object is larger and zero if neither object is larger according to the compareTo method for the first object @throws a ClassCastException if the first object is not comparable, or would throw such an exception when sent the compareTo message and the second object */ public int compare(Object o1, Object o2) { if (o1 instanceof Comparable) { counter++; return ((Comparable) o1).compareTo(o2); } else throw new ClassCastException(); } /** @return the current value of the comparison counter */ public int getCounter() { return counter; } /** Resets the comparison counter to 0. */ public void resetCounter() { counter = 0; } }