java 数组排序自定义_使用自定义排序顺序对象的数组列表进行排序

下面是关于排序对象的教程:

虽然我会给出一些例子,但我还是建议你读一读。

有多种方法对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,可能已经覆盖了空字段)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值