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
Collections.sort(accountList)
will work if Account implements Comparable. If not, you need to pass in a comparator
Collections.sort(accountList, new Comparator() {
public int compare(Account a, Account b) {
// Assumes account numbers are not null.
return a.getAccountNumber().compareTo(b.getAccountNumber());
}
});
From the javadoc:
public static> void sort(List list) Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the
Comparableinterface. Furthermore, all elements in the list must be mutually comparable (that is,e1.compareTo(e2)must not throw aClassCastExceptionfor any elementse1ande2in the list).