Java列表数组问题

Sof*_*tey 1 java arrays

我有以下课程:

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;
}
Run Code Online (Sandbox Code Playgroud)

这用于创建与我的主类的事务实例,所以我最终可以打印出长列表中的所有事务,如语句.

在我的主类帐户中,到目前为止我有这个代码:

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);


}
Run Code Online (Sandbox Code Playgroud)

我正在尝试在创建帐户时创建一个新事务并将其添加到ArrayList但我没有正确声明数组列表.我怎么能这样做?谢谢你的回复.

Ósc*_*pez 8

你忘了给它命名ArrayList.试试这个:

protected ArrayList<Transaction> transactions;
Run Code Online (Sandbox Code Playgroud)

遵循OO编程最佳实践,您应该使用接口类型而不是具体类来声明属性:

protected List<Transaction> transactions;
Run Code Online (Sandbox Code Playgroud)

另外,不要忘记在构造函数中实例化该属性:

transactions = new ArrayList<Transaction>();
Run Code Online (Sandbox Code Playgroud)

或者甚至更简单,如果您使用的是Java 7或更新版本:

transactions = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)

  • @ asaini007将List指定为'声明'类型比指定具体实现类型(如ArrayList)更通用.任何需要处理事务的方法都将具有ArrayList的参数类型,因为这是事务的类型.然而,如果您声明为List,则可以使用任何类型的列表.该事务列表可以是LinkedList或其他类型.我们的想法是保持类型更通用.如上所述,这没有错.请参阅此链接了解更多信息 http://stackoverflow.com/questions/2279030/type-list-vs-type-arraylist-in-java (2认同)