2

我的 java 程序遇到了一些问题,我不确定这是否是问题所在,但是在 araylist 内的对象上调用 mutator 方法会按预期工作吗?

例如

public class Account
{
    private int balance = 0;

    public Account(){}

    public void setAmount(int amt)
    {
         balance = amt;
    }
}


public class Bank
{
    ArrayList<Account> accounts = new ArrayList<Account>();

    public staic void main(String[] args)
    {
        accounts.add(new Account());
        accounts.add(new Account());
        accounts.add(new Account());

        accounts.get(0).setAmount(50);
    }
}

这会按预期工作还是有什么会导致这不?

4

2 回答 2

2

问题是否存在,但在 ArrayList 内的对象上调用 mutator 方法会按预期工作吗?

是的,如果您打算更新列表中的第一个帐户。请记住,数组列表不存储对象,而是对对象的引用改变其中一个对象不会更改存储在列表中的引用。

第一个帐户将被更新,当accounts.get(0)再次引用时,它将显示更新后的余额。

这是一个ideone.com 演示。(我刚刚修正了一些小错别字,例如staticaccounts声明前添加。)

for (int i = 0; i < accounts.size(); i++)
    System.out.println("Balance of account " + i + ": " +
                       accounts.get(i).balance);

产量

Balance of account 0: 50
Balance of account 1: 0
Balance of account 2: 0

希望这是您所期望的。

于 2011-05-28T19:05:26.070 回答
2

是的,这应该按预期工作。它与以下内容没有什么不同:

Account firstAccount = accounts.get(0);
firstAccount.setAmount(50);

请记住,ArrayList'get()方法返回存储在 中的实际对象ArrayList,而不是它的副本。

于 2011-05-28T19:05:46.070 回答