Sort an ArrayList of objects?

后端 未结 7 1765
轻奢々
轻奢々 2021-01-29 01:47

I need some help how to sort an ArrayList of objects. I have the superclass Account and two subclasses SavingsAccount and CreditAccount. Inside the Account class I have this met

7条回答
  •  灰色年华
    2021-01-29 02:06

    For a start, why is an account number being represented as a string? Is it a number, or is it text? Anyway, it's absolutely possible to sort your list using Collections.sort:

    Collections.sort(list, new Comparator() {
        @Override public int compare(Account x, Account y) {
            return x.getAccountNumber().compareTo(y.getAccountNumber();
        }
    });
    

    If that sorts them in the wrong sense for you (ascending instead of descending), reverse the comparison:

    Collections.sort(list, new Comparator() {
        @Override public int compare(Account x, Account y) {
            return y.getAccountNumber().compareTo(x.getAccountNumber();
        }
    });
    

    Note that as these are strings, it will sort them in lexicographic order. If you were using numbers instead, that wouldn't be a problem.

    An alternative which I wouldn't recommend in this case is to make Account implement Comparable. That's suitable when there's a single "natural" way of comparing two accounts - but I can see that you might want to sometimes sort by number, sometimes by the name of the account holder, sometimes by the funds within the account, sometimes by the date the account was created etc.

    As an aside, it's not clear that you really need to sort this at all - if you just need to find the largest account number, you don't need to sort it, you just need to iterate and remember the account with the largest number as you go:

    Account maxAccount = null;
    for (Account account : accounts) {
        if (maxAccount == null || 
            account.getAccountNumber().compareTo(maxAccount.getAccountNumber()) > 0) {
            maxAccount = account;
        }
    }
    

提交回复
热议问题