我的 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);
}
}
这会按预期工作吗?还是有什么原因导致这不能按预期工作?
最佳答案
Is the problem but would calling a mutator method on an object inside an ArrayList work as intended?
是的,如果您打算更新列表中的第一个帐户。 请记住,数组列表不存储对象,而是存储对对象的引用。改变其中一个对象不会更改存储在列表中的引用。 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
希望这正是您所期望的。
关于java - mutator 方法可以应用于 ArrayList 中的对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6163802/