在泛型方法Java中实现Comparable

时间:2018-04-04 20:38:01

标签: java generics methods compareto implements

在这段代码中,我的任务是实现Comparable。我知道我需要把实现Comparable但是后来我从编译器得到一个错误,说" Account不是抽象的,并且不会覆盖Comparable"中的抽象方法compareTo(Account)。

我知道我需要创建compareTo()方法,但我不知道如何。

我的确切任务是重写类Account,以便它实现Comparable接口。余额最低的帐户最小。创建一个main并通过创建3个Account对象来测试该类。将它们添加到ArrayList中。使用Collctions.sort()中的一种方法对其进行排序。

列表是否按您认为的那样排序?

以下是我的代码。

提前致谢!

//*******************************************************   
// Account.java .  
// A bank account class with methods to deposit to, withdraw from,  
// change the name on, charge a fee to, and print a summary of the 
// account.
//*******************************************************     

import java.util.*;

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


//----------------------------------------------  
//Constructor -- initializes balance, owner, and account number   
//----------------------------------------------

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

//----------------------------------------------
// Checks to see if balance is sufficient for withdrawal.
// If so, decrements balance by amount; if not, prints message.
//----------------------------------------------

   public String withdraw(double amount){
      String info="Insufficient funds";
      if (balance >= amount){
         balance=balance- amount;
         info= "Succeeded, the new balance is : "+ balance ;
      }

      return info;
    }

//----------------------------------------------
// Adds deposit amount to balance.
//----------------------------------------------

  public String deposit(double amount){
     String info=""  ;
     if( amount<0){
        info = " Wrong amount";
     }
     else{
        balance=balance+ amount;
        info=" Succeeded, the new balance is: " + balance;
     }

     return info;
  }

//----------------------------------------------
// Returns balance.
//----------------------------------------------
   public double getBalance(){
      return balance;
   }


//----------------------------------------------
// Returns a string containing the name, account number, and balance.
//----------------------------------------------

   public String toString(){
      return  " Numer: "+ acctNum+ " Balance: " + balance;
   }

//----------------------------------------------
// Returns accoutn number.
//----------------------------------------------

   public String getAcctNum(){
      return acctNum;
   }

   public boolean equals(Object other){
      // this is what you should do

      return true;
   }

   public int compareTo(Account a){
      return; 
   }    


   public static void main(String[] args){


   }
}

0 个答案:

没有答案