【问题标题】:Can mutator methods be applied to objects in an ArrayList?mutator 方法可以应用于 ArrayList 中的对象吗?
【发布时间】:2011-09-04 01:29:58
【问题描述】:

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

这会按预期工作吗?还是有什么东西会导致它不能按预期工作?

【问题讨论】:

    标签: java arrays mutation


    【解决方案1】:

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

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

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

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

    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
    

    希望这是您所期望的。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 2011-04-30
        • 1970-01-01
        • 2018-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-23
        • 2014-09-21
        相关资源
        最近更新 更多