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
I'm sorry to say your question is not very clear. What you mean by "I need to sort the account numbers to get the highest number of all accounts in the objects?" I guess you need to sort your ArrayList on the basis of accountNumber which is a String!!
To sort any objects in Java, they should implement the simple interface Comparable. Most of the Java built-in classes like String,Date etc already implement Comparable, and thats why we are able to sort them. For OUR classes WE should take the pain to tell the JVM on what basis it should sort OUR objects. You can tell this for Account class as shown below
public class Account implements Comparable{
private String accountNumber;
public int compareTo(Account anotherAcct) {
// Do null Check for anotherAcct
return this.getAccountNumber().compareTo(anotherAcct.getAccountNumber());
}
public String getAccountNumber() {
return accountNumber;
}
}
Now simply call Collections.sort(accountList).
Below is the sample test code and result
Account acct1 = new Account("AA1");
Account acct2 = new Account("BB1");
Account acct3 = new Account("AA2");
Account acct4 = new Account("1FF");
List accountList = new ArrayList();
accountList.add(acct1);
accountList.add(acct2);
accountList.add(acct3);
accountList.add(acct4);
Collections.sort(accountList);
System.out.println(accountList);
This printed
[Account [accountNumber=1FF], Account [accountNumber=AA1], Account [accountNumber=AA2], Account [accountNumber=BB1]]
ie in the decreasing alphabetical order. If you want the other way around (increasing order of alphabets) you can either call Collections.reverse(accountList) or go and change the compareTo() implementation as below.
public int compareTo(Account anotherAcct) {
// Do null Check for anotherAcct
//return this.getAccountNumber().compareTo(anotherAcct.getAccountNumber());
return anotherAcct.getAccountNumber().compareTo(this.getAccountNumber());
}
Sometimes you may be in a position where you cannot accomplish this using Comparable interface (may be because you don't have the source for that class or it is already implementing Comparable interface to sort on the basis of another attribute, say bank balance!). In this case you need to create a Comparator as below.
public class AccountNumberComparator implements Comparator{
@Override
public int compare(Account account1, Account account2) {
// do null checks for both account1 and account2
return account1.getAccountNumber().compareTo(account2.getAccountNumber());
}
}
Now simply call
Collections.sort(accountList,new AccountNumberComparator());
Advantage of this approach is you can create as many comparators you want like AccountBalanceComparator,AccountNameComparator etc on basis of different attributes, which can then be used to sort your list in different ways as you wish.