mutator 方法可以应用于 ArrayList 中的对象吗?
我的 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);
}
}
,这会按预期工作吗?或者是否有什么因素会导致这种情况无法按预期进行?
I'm having some trouble with my java program and I'm not sure if this is the problem but would calling a mutator method on an object inside an araylist work as intended?
For example
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);
}
}
Would this work as intended or is there something that would cause this not to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,如果您打算更新列表中的第一个帐户。 请记住,数组列表不存储对象,而是存储对对象的引用。改变其中一个对象不会更改存储在列表中的引用。
第一个帐户将被更新,当再次引用
accounts.get(0)
时,它将显示更新后的余额。这是一个演示它的 ideone.com 演示。 (我刚刚修复了一些小拼写错误,例如在
accounts
声明前面添加static
。)希望得到的结果
是您所期望的。
Yes, if your intention is to update the first account in the list. Keep in mind that the array list doesn't store objects, but references to objects. Mutating one of the objects won't change the reference stored in the list.
The first account will be updated, and when referencing
accounts.get(0)
again it will show the updated balance.Here's an ideone.com demo demonstrating it. (I've just fixed a few minor typos such as adding
static
in front of theaccounts
declaration.)yields
which hopefully is what you would expect.
是的,这应该按预期工作。它与:
记住,ArrayList 的 get() 方法返回存储在 ArrayList 中的实际对象,而不是它的副本。
Yes, that should work as intended. It is no different than:
Remember,
ArrayList
'sget()
method returns the actual object stored in theArrayList
, not a copy of it.