curMetrics.compareCnt++;
double d1 = values[i];
double d2 = values[j];
if (d1 == d2)
return 0;
else
return (d1 < d2? -1 : 1);
}
/* For extended classes to swap elements /
protected final void swap(int i, int j) {
curMetrics.swapCnt++;
double tmp = values[i];
values[i] = values[j];
values[j] = tmp;
}
/* Extended classes implement this -- used by sort /
protected abstract void doSort();
}
This class defines fields to hold the array being sorted (values) and a reference to a metrics object
(curMetrics) to track the measured operations. To ensure that these counts are correct, SortDouble
provides routines to be used by extended sorting classes when they need to examine data or perform
comparisons and swaps.
When you design a class, you can decide whether to trust its extended classes. The SortDouble class is
designed not to trust them, and that is generally the best way to design classes for others to extend. A guarded
design not only prevents malicious use, it also prevents bugs.
SortDouble carefully restricts access to each member to the appropriate level. It uses final on all its
non-abstract methods. These factors are all part of the contract of the SortDouble class, which includes
protecting the measurement of the sort algorithm from tampering. Making the methods final ensures that
no extended class overrides these methods to change behavior, and also allows the compiler and runtime
system to make them as efficient as possible.
SortMetrics objects describe the cost of a particular sorting run. The class has three public fields. Its only
task is to communicate data, so there is no need to hide that data behind accessor methods.
SortDouble.getMetrics returns a copy of the data so that it doesn't give out a reference to its internal
data. This prevents both the code that creates SortDouble objects and the code in the extended classes from
changing the data. Here is the SortMetrics class:
final class SortMetrics implements Cloneable {
public long probeCnt, // simple data probes
compareCnt, // comparing two elements
swapCnt; // swapping two elements
public void init() {
probeCnt = swapCnt = compareCnt = 0;
}
public String toString() {
return probeCnt + " probes " +
compareCnt + " compares " +
swapCnt + " swaps";
}
/* This class supports clone /
public SortMetrics clone() {
try {