I am looking to implement a sort feature for my address book application.
I want to sort an ArrayList
. Contact
Here's a tutorial about ordering objects:
Although I will give some examples, I would recommend to read it anyway.
There are various way to sort an ArrayList
. If you want to define a natural (default) ordering, then you need to let Contact
implement Comparable. Assuming that you want to sort by default on name
, then do (nullchecks omitted for simplicity):
public class Contact implements Comparable {
private String name;
private String phone;
private Address address;
public int compareTo(Contact other) {
return name.compareTo(other.name);
}
// Add/generate getters/setters and other boilerplate.
}
so that you can just do
List contacts = new ArrayList();
// Fill it.
Collections.sort(contacts);
If you want to define an external controllable ordering (which overrides the natural ordering), then you need to create a Comparator:
List contacts = new ArrayList();
// Fill it.
// Now sort by address instead of name (default).
Collections.sort(contacts, new Comparator() {
public int compare(Contact one, Contact other) {
return one.getAddress().compareTo(other.getAddress());
}
});
You can even define the Comparator
s in the Contact
itself so that you can reuse them instead of recreating them everytime:
public class Contact {
private String name;
private String phone;
private Address address;
// ...
public static Comparator COMPARE_BY_PHONE = new Comparator() {
public int compare(Contact one, Contact other) {
return one.phone.compareTo(other.phone);
}
};
public static Comparator COMPARE_BY_ADDRESS = new Comparator() {
public int compare(Contact one, Contact other) {
return one.address.compareTo(other.address);
}
};
}
which can be used as follows:
List contacts = new ArrayList();
// Fill it.
// Sort by address.
Collections.sort(contacts, Contact.COMPARE_BY_ADDRESS);
// Sort later by phone.
Collections.sort(contacts, Contact.COMPARE_BY_PHONE);
And to cream the top off, you could consider to use a generic javabean comparator:
public class BeanComparator implements Comparator
which you can use as follows:
// Sort on "phone" field of the Contact bean.
Collections.sort(contacts, new BeanComparator("phone"));
(as you see in the code, possibly null fields are already covered to avoid NPE's during sort)