基于名称对联系人的ArrayList排序? [英] Sorting an ArrayList of Contacts based on name?

查看:249
本文介绍了基于名称对联系人的ArrayList排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

对对象集合进行排序

一直在做一个地址簿应用程序,几乎完成了所有的关键功能,但我正在实现一个排序功能的程序。

Ok so I have a been making an addressbook application and have pretty much finished all the key features but I am looking to implement a sort feature in the program.

我想排序一个Arraylist一个名为Contact(contactArray)的类型,它是一个包含四个字段的单独类;姓名,家庭电话号码,手机号码和地址。
所以我正在研究使用集合排序,但不知道如何实现这个。

I want to sort an Arraylist which is of a type called Contact (contactArray) which is a separate class which contains four fields; name, home number, mobile number and address. So I was looking into using the collection sort yet am not sure how i'd implement this.

这是正确的排序,我应该使用/

Is this the right sort I should be using / is it possible to use or should I look into making a custom sort?

推荐答案

这里有一个关于排序对象的教程:

Here's a tutorial about ordering objects:

  • The Java Tutorials - Collections - Object Ordering

虽然我将给出一些示例,

Although I will give some examples, I would recommend to read it anyway.

有多种方法可以对 ArrayList 进行排序。如果您要定义自然(默认)订单,则需要让联系 http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html =nofollow noreferrer> 可比较 。假设你想在 name 上默认排序,然后执行(为了简单省略nullchecks):

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<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


If you want to define an external controllable ordering (which overrides the natural ordering), then you need to create a 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());
    }
}); 






您甚至可以定义 > 中的比较器,以便您可以重复使用它们,而不是每次都重新创建:


You can even define the Comparators 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<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 sort)

这篇关于基于名称对联系人的ArrayList排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆