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
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;
}
}