我有一个公共类帐户,我想使用类似的帐户来实现,而我的问题如下:

在比较中,如何使余额最低的帐户“最小”?

public class Account implements Comparable<Account>{
  private double balance;
  private String acctNum;

  public Account(String number, double initBal){
      balance = initBal;
      acctNum = number;
  }
  public double getBalance(){
      return balance;
  }
  .....


 public int compareTo(Account other) {
         ????????
  }

最佳答案

compareTo方法必须返回:


一个负整数,如果它小于其他整数,
如果等于其他则为零
正整数(如果大于或等于此整数)


如果值接近return this.balance - other.balanceDouble.MAX_VALUE,仅执行Double.MIN_VALUE可能会给出无效的结果,因此应使用Double.compare

public int compareTo(Account other) {
    return Double.compare(this.balance, other.balance);
}

07-28 02:31
查看更多