Sort an ArrayList of objects?

后端 未结 7 1851
轻奢々
轻奢々 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 01:59

    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 Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

提交回复
热议问题