The following Comparator class is attempting to arrange BankAccount objects by a
ID: 3593271 • Letter: T
Question
The following Comparator class is attempting to arrange BankAccount objects by account name, breaking ties by account balance. But the code has some syntax errors and some logic errors. What is wrong with the code? How would you correct it?
import java.util.*;
public class AccountComparator extends Comparator {
public int compareTo (BankAccount account2) {
if (!this.getName().equals(account2.getName())) {
return this.getName().compareTo(account2.getName());
} else {
return this.getBalance() - account2.getBalance();
}
}
}
Explanation / Answer
1. Comparator is Interface so classes will implement it , rather than extending
2. Comparator has compare Method and not compareTo, so we need to implement compare
Corrected form
public class AccountComparator implements Comparator {
@Override
public int compare(BankAccount account2) {
if ( this.getName().compareTo( account2.getName() ) > 0)
return 1;
else if (this.getName().compareTo(account2.getName()) < 0)
return -1;
else
return this.getBalance() - account2.getBalance();
}
}
Thanks, let me know if there is any concern.