Java使用自定义排序顺序对对象的ArrayList进行排序
我正在为我的通讯录应用程序实现排序功能。
我想排序一个ArrayList<Contact> contactArray
。Contact
是一个包含四个字段的类:姓名,家庭电话,手机号码和地址。我想继续name
。
如何编写自定义排序功能来做到这一点?
回答:
这是有关订购对象的教程:
Java教程-集合-对象排序
尽管我会举一些例子,但我还是建议你阅读它。
有多种排序方式ArrayList
。如果要定义自然的(默认)排序,则需要让ContactImplement
实现Comparable
。假设你想默认在上进行排序name,然后执行(为简单起见,省略了nullchecks):
public class Contact implements Comparable<Contact> { 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<Contact> contacts = new ArrayList<Contact>();// Fill it.
Collections.sort(contacts);
如果要定义外部可控排序(覆盖自然排序),则需要创建一个Comparator:
List<Contact> contacts = new ArrayList<Contact>();// Fill it.
// Now sort by address instead of name (default).
Collections.sort(contacts, new Comparator<Contact>() {
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<Contact> COMPARE_BY_PHONE = new Comparator<Contact>() {
public int compare(Contact one, Contact other) {
return one.phone.compareTo(other.phone);
}
};
public static Comparator<Contact> COMPARE_BY_ADDRESS = new Comparator<Contact>() {
public int compare(Contact one, Contact other) {
return one.address.compareTo(other.address);
}
};
}
可以如下使用:
List<Contact> contacts = new ArrayList<Contact>();// 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<Object> { 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<Object>) o1).compareTo(o2));
}
}
你可以使用以下方法:
// Sort on "phone" field of the Contact bean.Collections.sort(contacts, new BeanComparator("phone"));
(如你在代码中所见,可能的空字段已经被覆盖以避免在排序过程中出现NPE)
以上是 Java使用自定义排序顺序对对象的ArrayList进行排序 的全部内容, 来源链接: utcz.com/qa/427089.html