开发者

Can mutator methods be applied to objects in an ArrayList?

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 in开发者_Go百科t 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?


Is the problem but would calling a mutator method on an object inside an ArrayList work as intended?

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 the accounts declaration.)

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

yields

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

which hopefully is what you would expect.


Yes, that should work as intended. It is no different than:

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

Remember, ArrayList's get() method returns the actual object stored in the ArrayList, not a copy of it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜