在实现比较器接口以实现对象的自然排序时:
说如果我们有类帐户:
class Account
{
Account(String name, int id)
int balance()
void deposit(int n)
}
我们想按顺序对两个账户的账户余额进行排序
这两种方法有什么区别?
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;
}
}