-3

how can I sort an Array after deleting one value?

e.g. {1,2,3,4,5} --> {1,2,null,4,5} --> {1,2,4,5,null}.

public boolean removeNumber(int accountNumber) {
    for(int i = 0; i < Account.length; i++) {
        if(Account[i].getAccountNumber() == (accountNumber)) {
            Account[i] = null;
        }

2 Answers2

1

You can follow this way to achieve this :

  1. You need to find the accounts that have the accountNumber you're looking for
  2. you set them to null on the array
  3. You sort the array with a custom Comparator :
    • if an element is null it has to go at the end
    • if both are not-null you compare their accountNumber
public boolean removeNumber(int accountNumber) {
    for (int i = 0; i < Account.length; i++) {
        if (Account[i].getAccountNumber() == accountNumber) {
            Account[i] = null;
        }
    }
    Arrays.sort(Account, (o, p) -> {
        if (o == null)
            return 1;
        if (p == null)
            return -1;
        return Integer.compare(o.getAccountNumber(), p.getAccountNumber());

    });
    return true;
}

Tips :

  • follow naming conventions : camelCasefor attriutes ==> Account[] becomes account[]
  • use .equals() when you are comparing object, for an int == is right
azro
  • 53,056
  • 7
  • 34
  • 70
1

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)));
Andreas
  • 154,647
  • 11
  • 152
  • 247