Milo StaKic
Milo StaKic

Reputation: 31

How to remove value from Array in Method?

I have written this method to remove a value (the account from the accounts array).

   public boolean removeAccount(BankAccount accountNumber){
        for(int i = accounts.length - 1; i >= 0; i--) {
            if(accounts[i] == accounts.length+1) {
               accounts.length;
}
return -1
}

Would this be a proper way to remove an element from an array?

Upvotes: 0

Views: 81

Answers (1)

Denis
Denis

Reputation: 1229

The code you are using to remove element is wrong. Also, I would recommend you to use List.Since if you remove an element from array you will need to change the index to -1 for all the elements that comes after the removed element. Also, array will have a blank value which will cause problems.

Updating your code to List. It should be something like this -

public void removeAccount(BankAccount accountNumber,ArrayList accounts)
{
    int length = accounts.size();
    for(int i = 0; i<length; i++) 
    {
        if(accountNumber.equals(accounts.get(i))) //*
        {
           accounts.remove(i);
           break;
         }
    }
}
  • In you code you never compare the objects. you are comparing an object with integer.

  • Also, In your code at the first iteration of loop method will return -1.

  • You call accounts.length in each iteration two times. I don't think it is a good practice. You should store the length in a variable and use it.

Upvotes: 1

Related Questions