Java:Collections.sort导致错误 - 找不到合适的方法

时间:2015-10-30 01:27:02

标签: java class inheritance interface

我正在尝试为类Bank Bank实现Comparable的接口,我覆盖了Bank帐户的compareTo方法,但在尝试使用Collections.sort时,我收到错误:

BankAccountTester.java:40: error: no suitable method found for sort(ArrayList<BankAccount>)
  Collections.sort(list);

为什么会这样?

我的代码位于银行帐户和测试人员的下方:

    /**
  A class to test the BankAccount class.
*/
import java.util.ArrayList; 
import java.util.Collections;

public class BankAccountTester
{

   public static void main(String[] args)
   {

      BankAccount bank1 = new BankAccount(30); 

      BankAccount bank2 = new BankAccount(15); 

      BankAccount bank3 = new BankAccount(10);  
      BankAccount bank4 = new BankAccount(5);
      BankAccount bank5 = new BankAccount(20);


      // Put the rectangles into a list 


      ArrayList<BankAccount> list = new ArrayList<BankAccount>(); 


      list.add(bank1); 

      list.add(bank2); 

      list.add(bank3); 
      list.add(bank4);
      list.add(bank5);



      // Call the library sort method 

      Collections.sort(list);  



      // Print out the sorted list 

      for (int i = 0; i < list.size(); i++) 
      {

         BankAccount b = list.get(i); 

         System.out.println(b.getBalance()); 
      }

  }
}

银行帐户类:

 /**
       A bank account has a balance that can be changed by 
       deposits and withdrawals.
    */
    public class BankAccount implements Comparable<BankAccount>
    {  
        private double balance;
       /**
          Constructs a bank account with a zero balance.
       */
       public BankAccount()
       {   
        // this.balance = 0;
         this(0);

       }

       /**
          Constructs a bank account with a given balance.
          @param initialBalance the initial balance
       */
       public BankAccount(double balance)
       {   
          this.balance = balance;
       }

       /**
          Deposits money into the bank account.
          @param amount to deposit
       */
       public void deposit(double amount)
       {  
          balance = balance + amount;

       }

       /**
          Withdraws money from the bank account.
          @param amount  to withdraw
       */
       public void withdraw(double amount)
       {   
          balance = balance - amount;

       }

       /**
          Gets the current balance of the bank account.
          @return the current balance
       */
       public double getBalance()
       {   
          return balance;
       }

       public int compareTo(BankAccount otherObject) {
          BankAccount other = (BankAccount) otherObject;

          if (this.balance < other.balance) { return -1; }

          if(this.balance > other.balance) { return 1; }

          return 0;
       }

    }

0 个答案:

没有答案