这是一个关于订购对象的教程:
虽然我会给出一些例子,但我仍然建议你阅读它.
有多种方法可以对ArrayList进行排序.如果你想定义一个自然(默认)排序,那么你需要让联系人实现Comparable.假设你想在名称上默认排序,那么为了简单起见省略了nullchecks:
public class Contact implements Comparable {
private String name;
private String phone;
private Address address;
public int compareTo(Contact other) {
return pareTo(other.name);
}
// Add/generate getters/setters and other boilerplate.
}
这样你就可以做到
List contacts = new ArrayList();
// Fill it.
Collections.sort(contacts);
如果要定义外部可控排序(它会覆盖自然排序),则需要创建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());
}
});
您甚至可以在Contact本身中定义Comparators,以便您可以重复使用它们,而不是每次都重新创建它们:
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 pareTo(other.phone);
}
};
public static Comparator COMPARE_BY_ADDRESS = new Comparator() {
public int compare(Contact one, Contact other) {
return pareTo(other.address);
}
};
}
可以使用如下:
List contacts = new ArrayList();
// Fill it.
// Sort by address.
Collections.sort(contacts, PARE_BY_ADDRESS);
// Sort later by phone.
Collections.sort(contacts, PARE_BY_PHONE);
最重要的是,您可以考虑使用通用的javabean比较器:
public class BeanComparator implements Comparator {
private String getter;
public BeanComparator(String field) {
this.getter = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
}
public int compare(Object o1, Object o2) {
try {
if (o1 != null && o2 != null) {
o1 = o1.getClass().getMethod(getter, new Class[0]).invoke(o1, new Object[0]);
o2 = o2.getClass().getMethod(getter, new Class[0]).invoke(o2, new Object[0]);
}
} catch (Exception e) {
// If this exception occurs, then it is usually a fault of the developer.
throw new RuntimeException("Cannot compare " + o1 + " with " + o2 + " on " + getter, e);
}
return (o1 == null) ? -1 : ((o2 == null) ? 1 : ((Comparable) o1).compareTo(o2));
}
}
您可以使用如下:
// Sort on "phone" field of the Contact bean.
Collections.sort(contacts, new BeanComparator("phone"));
(正如您在代码中看到的那样,在排序过程中可能已经覆盖了空字段以避免NPE)