0

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?

4
  • you pass accountNumber as argument but you are not using it, is this on purpose ? Commented Nov 6, 2016 at 23:50
  • 2
    Use a List... Commented Nov 6, 2016 at 23:50
  • 1
    I agree with @Reimeus. Also, your code has a missing bracket + returns -1 (the method return type is boolean). Commented Nov 6, 2016 at 23:52
  • When you create an array, its size will be whatever size you told it when you created the array. You cannot make the array larger or smaller. To "remove" an element, you'd have to create a new array whose size is one smaller, and copy the elements you want from the old one to the new one. Using a List (particularly an ArrayList) is easier since it does allow the size to change dynamically. Commented Nov 7, 2016 at 0:26

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

I suggest you use ArrayList<BankAccount> instead of just ArrayList. Raw generic types shouldn't be encouraged.
Thanks just missed it.

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.