我有以下类(class):
public class Transaction {
public String Type;
public double Amount;
public double Balance;
Transaction(String Type,double Amount,double Balance){
this.Type = Type;
this.Amount = Amount;
this.Balance = Balance;
}
public String toString(){
String s = " Type: "+ Type +"\n Amount: "+ Amount+ "\n Balance: "+Balance;
return s;
}
这用于通过我的主类创建交易实例,因此我最终可以像语句一样打印出一长串所有交易。
到目前为止,在我的主类帐户中我有以下代码:
public class Account {
private String name;
private double balance;
public double initDeposit;
protected ArrayList<Transaction>;
public Account(String name, double initDeposit){
this.balance =initDeposit;
this.name = name;
Transaction a = new Transaction("Creation",initDeposit,balance);
}
我试图在创建帐户时创建一个新事务并将其添加到 ArrayList,但我没有正确声明数组列表。我怎么能那样做?感谢您的任何回复。
最佳答案
您忘记为 ArrayList
命名。试试这个:
protected ArrayList<Transaction> transactions;
并且遵循 OO 编程最佳实践,您应该使用接口(interface)类型而不是具体类来声明属性:
protected List<Transaction> transactions;
也不要忘记在构造函数中实例化属性:
transactions = new ArrayList<Transaction>();
或者更简单,如果您使用的是 Java 7 或更新版本:
transactions = new ArrayList<>();
关于Java列表数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21687958/