繁体   English   中英

将多个对象传递给 JAVA 中的方法

[英]Passing multiple Objects to method in JAVA

我试图将定义的 2 个对象(具有一个属性“金额”的交易)传递给另一种将接收交易列表的方法

这是主要的:

public class Test {

public static void main(String[] args) {    
    // Here is when the Transaction was sent twice with differents amounts
    BankAccount saving = new SavingAccount("Raul", 1000d, new Transaction(500d), new Transaction(-500d));
}

}

这是 Object 交易

class Transaction {

    private Double amount;
    public Transaction(Double amount) {
        super();
        this.amount = amount;
    }
    public Double getAmount() {
        return amount;
    }
    public void setAmount(Double amount) {
        this.amount = amount;
    }

}

这是银行 class

class BankAccount {

private String name;
private Double amount;

public BankAccount(String name, Double amount) {
    super();
    this.name = name;
    this.amount = amount;
}

public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Double getAmount() {
    return amount;
}
public void setAmount(Double amount) {
    this.amount = amount;
}

}

最后 SavingAccount 将对交易列表进行一些操作

class SavingAccount extends BankAccount{
public SavingAccount(String name, Double amount, List<Transaction> transaction) {
    super(name, amount);
    // Do something with the list of transactions
}

}

我的第一个解决方案是创建一个 Transaction 类型的 List 并传递给该方法并且它有效,但我的解决方案被拒绝了......

public class Test {

public static void main(String[] args) {    

    List<Transaction> transaction = new ArrayList<Transaction>();
    transaction.add(new Transaction(5000d));
    transaction.add(new Transaction(-5000d));
    BankAccount saving = new SavingAccount("Raul", 1000d, transaction);
}

}

在不首先定义 ArrayList 的情况下,我该如何维护这些对象作为参数的发送?

您可以更改 SavingAccount 构造函数的签名以使用可变参数来接收您想要的 Transaction 对象的数量:

 public SavingAccount(String name, BigDecimal amount, Transaction ... transactions) {}

或者您可以简单地使用两个 Transaction 对象:

public SavingAccount(String name, BigDecimal amount, Transaction transaction1, Transaction transaction2) {}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM