簡體   English   中英

公開課 <Generic type> 實現可比

[英]Public class <Generic type> implements Comparable

我有一個公共類帳戶,想要以可比較的方式實施,我的問題是:

如何使余額最低的帳戶在我的比較中“最小”?

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.balance如果值接近Double.MAX_VALUEDouble.MIN_VALUEreturn this.balance - other.balance可能給出無效結果,因此您應該使用Double.compare

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

最簡單的實現方法是將Double用作balance類型,然后簡單地調用compareTo方法:

return balance.compareTo(other);

我並不是說這是最好的,但是對於開始來說已經足夠了。

請注意,處理null取決於您實現。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM