Sorting an ArrayList of Contacts based on name?

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

        }

        ...

    }

}