Reputation: 2117
There is a code that I don't really understand from Sedgewick's Algorithms book, specifically the part on Comparators. I understand very well how everything else works, e.g., the algorithm provided, the intention of using Comparators vs Comparable, etc. However, the one thing that I don't seem to get are the parameters of the compare(Transaction v, Transaction w) method in the static class. For example, the array of Objects is passed and held by another Object reference in sort. When the helper method, less(), is invoked, the two elements of the Object array are held by another Object references. But this is what I don't get: In
public static class WhoOrder implements Comparator<Transaction> {
public int compare(Transaction v, Transaction w) {
return v.who.compareTo(w.who);
}
}
The Object references seem to have been replaced by Transaction references. How is this so? With polymorphism, you'd have to use an explicit downcast, but this seems to bypass that. My guess is that it's because of the parameterized type, but I don't know why that is.
The class which contains a static class that implements Comparator
public class Transaction {
private final String who; // customer
private final Date when; // date
private final double amount; // amount
...
// ascending order of account number
public static class WhoOrder implements Comparator<Transaction> {
public int compare(Transaction v, Transaction w) {
return v.who.compareTo(w.who);
}
}
public static void main(String[] args) {
...
Arrays.sort(a, new Transaction.WhoOrder());
}
The sorting class:
// use a custom order and Comparator interface - see Section 3.5
public static void sort(Object[] a, Comparator c) {
int N = a.length;
for (int i = 0; i < N; i++) {
for (int j = i; j > 0 && less(c, a[j], a[j-1]); j--) {
exch(a, j, j-1);
}
}
}
// is v < w ?
private static boolean less(Comparator c, Object v, Object w) {
return (c.compare(v, w) < 0);
}
// exchange a[i] and a[j]
private static void exch(Object[] a, int i, int j) {
Object swap = a[i];
a[i] = a[j];
a[j] = swap;
}
Upvotes: 1
Views: 556
Reputation: 66263
WhoOrder
is implemented as a Comparator
with Transaction
as its type parameter so the implementation of compare
accepts two Transactions
. However, the less
method takes a raw Comparator
(without a type). For backwards compatibility when you do this the generics type checking is disabled so you are able to pass 2 Objects
to compare
.
Upvotes: 2