排序 ArrayList<class>在 Java 中 [英] Sort ArrayList&lt;class&gt; in Java

查看:49
本文介绍了排序 ArrayList<class>在 Java 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这门课:

public class Contact {
private  String firstname;
private String lastname;
private List<Integer> phoneNumber;
private Scanner in;
public Contact(){
    phoneNumber = new ArrayList<>();
    firstname = lastname = "";
    in = new Scanner(System.in);
}
public void setFirstName(){
    firstname = in.nextLine();
} 
public  void setLastName(){
    lastname = in.nextLine();
}
public void setPhoneNumber(){
    phoneNumber.add(in.nextInt());
}
public String getFirstName(){
    return firstname;
}
public  String getLastName(){
    return lastname;
}
public  Integer getPhoneNumber(int position){
    return phoneNumber.get(position);
}
}

现在我想制作一个有我的联系人的类电话簿..我想用

Now I want to make a class PhoneBook which have my contacts.. I thought to make it with

Arraylist<Contact>

因为它没有固定大小..当我想按姓氏对这个数组列表进行排序时,我该怎么办?

because it won't have a fixed size.. When I want to sort this arraylist by Lastname what would I do?

推荐答案

你的 Contact 类需要实现 Comparable 接口...然后你可以使用 Collections.sort(list) 对列表进行排序.

Your Contact class needs to implement the Comparable interface... Then you can use Collections.sort(list) to sort the list.

如果您想要多种排序方式,那么您还可以创建一个实现 Comparator 接口的类.您可以创建多个比较器(或使一个可配置),然后您可以将比较器作为第二个参数传递给 Collections.sort

If you want to have multiple ways of sorting, then you could also make a class that is implementing the Comparator interface. You can create multiple comparators (or make one configurable), then you can pass the comparator as second parameter to Collections.sort

这是一个解释比较器解决方案的链接:http://www.vogella.com/blog/2009/08/04/collections-sort-java/

Here is a link explaining the comparator solution: http://www.vogella.com/blog/2009/08/04/collections-sort-java/

这篇关于排序 ArrayList<class>在 Java 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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