[英]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_VALUE
或Double.MIN_VALUE
, return 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.