下面是关于排序对象的教程:
虽然我会给出一些例子,但我还是建议你读一读。
有多种方法对ArrayList..如果要定义天然(违约)定序,那你就得让Contact实施Comparable..假设您想在默认情况下对name,然后执行(为简单起见省略了空检查):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.}
这样你就可以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());
}});
您甚至可以定义Comparator在Contact这样您就可以重用它们,而不是每次都重新创建它们: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);
}
};}
可用于以下方面: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);
如果你想把上面涂掉,你可以考虑用一个通用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,可能已经覆盖了空字段)