2

I have created a method that should ideally take a single Account object and then add it an array of accounts, but the problem is that the entered Account "add" overrides every existing Account in the array and sets them all equal to add and I am not sure why. Additionally, prior to doing anything the array accounts gets set to the entered account "add" and I am completely puzzled as to why this is. Sorry if I am missing something blatantly obvious, but any help would be appreciated.

public void addAccount(Account add)
{
  if (count < accounts.length)
  {
    accounts[count] = add;
    count++;
    System.out.println("Added " + add.toString() + " to list of accounts");
  }
  else
  {
    accounts = expand(10);
    addAccount(add);
  }
}
2
  • Considering this is getting down voted I think I submitted my question poorly or improperly, for that I apologize, please feel free to explain how I can improve any future questions I ask here. Commented Mar 26, 2012 at 5:13
  • IMHO the downvotes were a little harsh. You could have explained the problem better, but it was clear enough. Welcome to SO :-) Commented Mar 26, 2012 at 5:22

1 Answer 1

1

Your addAccount() method looks ok, your problem is most likely in your call to it. Based on how I've seen people get the same problem earlier, the reason you're seeing it is most likely that you're doing something like;

Account account = new Account();
for(int i=0; i<10; i++)
{
    account.Name = "Account #" + i;
    accAccount(account);
}

...which would create one account, change it, add it, change it, add it etc. What you need to remember is that you're creating a single account, so changing it after adding it will change the values you earlier added to the array too. What you'd need to do is;

for(int i=0; i<10; i++)
{
    Account account = new Account();
    account.Name = "Account #" + i;
    accAccount(account);
}

which will create 10 accounts and would work better.

Sign up to request clarification or add additional context in comments.

2 Comments

The problem was exactly that, I had declared my account variable globally, but by declaring it locally within a loop it resolved my problem. Thank you very much.
@Vore Now that Joachim has provided you the answer (+1 good mind-reading, Joachim), you should "accept" his answer by clicking the checkmark above left.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.