简体   繁体   English

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

[英]Passing multiple Objects to method in JAVA

Im tried to passing 2 Objects defined (Transaction with one attribute "amount") to another method that will receive the list of Transaction我试图将定义的 2 个对象(具有一个属性“金额”的交易)传递给另一种将接收交易列表的方法

This is the main:这是主要的:

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

} }

This is the Object Transaction这是 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;
    }

} }

and This is the Bank class这是银行 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;
}

} }

and finally the SavingAccount will do some operations with the List of transactions最后 SavingAccount 将对交易列表进行一些操作

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

} }

My first solution was to create a List of type Transaction and pass to the method and it Works, but my solution was rejected...我的第一个解决方案是创建一个 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);
}

} }

How can i do to maintain the send of that objects as parameters without define a ArrayList first?在不首先定义 ArrayList 的情况下,我该如何维护这些对象作为参数的发送?

You can change the signature of your SavingAccount constructor to use varargs that receive how many Transaction objects that you want:您可以更改 SavingAccount 构造函数的签名以使用可变参数来接收您想要的 Transaction 对象的数量:

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

Or you can use simply two Transaction objects:或者您可以简单地使用两个 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