Different types of comparables
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;
     }
}
第二个更安全,因为第一个可以提供极端值的错误结果(整数溢出)。
As Puce already wrote, the second is safer where Integer overflow would give you unexpected output. If you want it short and safe at the same time, you can write:
return Integer.compare(acc1.balance(), acc2.balance());
上一篇: 使用可比较的或比较器来实施BST
下一篇: 不同类型的可比较物
