我尝试在 BankAccounts 的数组列表上实现可比较的接口,但是,在尝试编译和运行测试器类的主要方法时,我遇到了重大错误,特别是关于 Collection.sort(list) 行。据说它无法识别语法..在网上和通过javadoc查看,我找不到我错的地方..
public class BankAccount implements Comparable { //QUESTION 2.1
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
*/
private int accountNumber;
private double balance;
/**
Constructs a bank account with a zero balance
@param anAccountNumber the account number for this account
*/
public BankAccount(int anAccountNumber)
{
accountNumber = anAccountNumber;
balance = 0;
}
/**
Constructs a bank account with a given balance
@param anAccountNumber the account number for this account
@param initialBalance the initial balance
*/ public BankAccount(int anAccountNumber, double initialBalance) {
accountNumber = anAccountNumber; 余额=初始余额;}
/**
Gets the account number of this bank account.
@return the account number
*/
public int getAccountNumber()
{
return accountNumber;
}
/**
Deposits money into the bank account.
@param amount the amount to deposit
*/
public void deposit(double amount)
{
double newBalance = balance + amount;
balance = newBalance;
}
/**
Withdraws money from the bank account.
@param amount the amount to withdraw
*/
public void withdraw(double amount)
{
double newBalance = balance - amount;
balance = newBalance;
}
/**
Gets the current balance of the bank account.
@return the current balance
*/
public double getBalance()
{
return balance;
}
public int compareTo (BankAccount temp) {
if (balance<temp.balance)
return -1;
if (balance==temp.balance)
return 0;
return 1;
}
}
public class TestSortedBankAccounts {
public static void main(String[] args) {
// Put bank accounts into a list
ArrayList<BankAccount> list = new ArrayList<BankAccount>();
BankAccount ba1 = new BankAccount(100, 500); //Constructor acctNumber and balance
BankAccount ba2 = new BankAccount(200, 10000);
BankAccount ba3 = new BankAccount(300, 400);
BankAccount ba4 = new BankAccount(600, 0);
BankAccount ba5 = new BankAccount(800, 50);
list.add(ba1);
list.add(ba2);
list.add(ba3);
list.add(ba4);
list.add(ba5);
// 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());
}
}
}
更新:TestSortedBankAccounts.java:26:错误:没有找到适合 sort(ArrayList) Collections.sort(list) 的方法;^ 方法 Collections.sort(List,Comparator) 不适用(无法从参数实例化,因为实际参数列表和形式参数列表的长度不同)方法 Collections.sort(List) 不适用(推断类型不符合声明的边界)推断:BankAccount bound(s): Comparable) 其中 T#1,T#2 是类型变量:T#1 扩展方法 sort(List,Comparator) 中声明的对象 T#2 扩展方法 sort(List) 中声明的 Comparable 1错误