Since your original array is already sorted, and assuming that only one Account
can have that particular accountNumber
, there is no need to sort the array again. Just locate the element to remove, then shift everything after that element down one position, and null out the newly-freed element.
I've renamed the Account
field to accounts
to follow Java naming conventions, to make a clearer distinction between the array (accounts
) and the class (Account
), both for the future developers looking at the code, and for the Java compiler.
public boolean removeNumber(int accountNumber) {
for (int i = 0; i < accounts.length; i++) {
if (accounts[i].getAccountNumber() == accountNumber) {
System.arraycopy(accounts, i + 1, accounts, i, accounts.length - i - 1);
accounts[accounts.length - 1] = null;
return true; // Found and removed
}
}
return false; // Not found, so nothing removed
}
Now, if you insist on sorting the array, you can do it like this in Java 8+:
Arrays.sort(accounts, Comparator.nullsLast(Comparator.comparing(Account::getAccountNumber)));