0

I have an Public class Account that i want to implement with comparable and my question is the following:

how can I make that the account with the lowest balance is the "smallest" in my comparison?.

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) {
         ????????
  }
JohnBanana
  • 45
  • 6
  • 1
    Did you read [the docs](https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html#compareTo%28T%29) for that method? – resueman Apr 11 '16 at 20:33
  • [This method](https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#compare(double,%20double)) might be helpful to you. – Andy Turner Apr 11 '16 at 20:35

2 Answers2

2

The compareTo method must return:

  • a negative integer if this is less than other,
  • zero if this is equal to other
  • a positive integer if this or greater than other

Just doing return this.balance - other.balance can give invalid results if values are near Double.MAX_VALUE or Double.MIN_VALUE, so you should use Double.compare:

public int compareTo(Account other) {
    return Double.compare(this.balance, other.balance);
}
ericbn
  • 10,163
  • 3
  • 47
  • 55
0

The simplest way to implement is to use a Double as the type for balance and simply call compareTo method:

return balance.compareTo(other);

I'm not saying that this is the best but it is good enough for a start.

Note that handling nulls is up to you to implement.

Adam Arold
  • 29,285
  • 22
  • 112
  • 207