when implementing the comparator interface to achieve natural ordering of objects :
say if we had the class Account:
class Account
{
Account(String name, int id)
int balance()
void deposit(int n)
}
we wanted to sort the Account balances of two accounts in order
whats the diffrence between these two methods?
public class comparebalances implements Comparable <Account>
{
public int compare (Account acc1, Account acc2)
{
return acc1.balance()-acc2.balance();
}
}
public class comparebalances implements Comparable <Account>
{
public int compare (Account acc1, Account acc2)
{
if (acc1.balance()> acc2.balance())
return 1;
else if (acc1.balance()< acc2.balance())
return -1;
else if (acc1.balance()==acc2.balance())
return 0;
}
}
The second one is safer, as the first one can provide wrong results for extreme values (integer overflow).