Sorting an ArrayList of objects using a custom sorting order

后端 未结 11 1513
说谎
说谎 2020-11-22 00:14

I am looking to implement a sort feature for my address book application.

I want to sort an ArrayList contactArray. Contact

11条回答
  •  一整个雨季
    2020-11-22 00:35

    This page tells you all you need to know about sorting collections, such as ArrayList.

    Basically you need to

    • make your Contact class implement the Comparable interface by
      • creating a method public int compareTo(Contact anotherContact) within it.
    • Once you do this, you can just call Collections.sort(myContactList);,
      • where myContactList is ArrayList (or any other collection of Contact).

    There's another way as well, involving creating a Comparator class, and you can read about that from the linked page as well.

    Example:

    public class Contact implements Comparable {
    
        ....
    
        //return -1 for less than, 0 for equals, and 1 for more than
        public compareTo(Contact anotherContact) {
            int result = 0;
            result = getName().compareTo(anotherContact.getName());
            if (result != 0)
            {
                return result;
            }
            result = getNunmber().compareTo(anotherContact.getNumber());
            if (result != 0)
            {
                return result;
            }
            ...
        }
    }
    

提交回复
热议问题