I am looking to implement a sort feature for my address book application.
I want to sort an ArrayList
. Contact
This page tells you all you need to know about sorting collections, such as ArrayList.
Basically you need to
Contact
class implement the Comparable
interface by
public int compareTo(Contact anotherContact)
within it.Collections.sort(myContactList);
,
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;
}
...
}
}