简体   繁体   中英

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 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM