告诉HashSet如何对数据进行排序 [英] Telling HashSet how to sort the data

查看:1195
本文介绍了告诉HashSet如何对数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个HashSet(或任何集合类型 - 但我认为HashSet最适合我),无论插入什么内容都会保持顺序。这是我正在进行的联系经理项目。
我一直在试验,下面的例子。

I'm trying to create a HashSet (or any collection type - but I think HashSet will suit me best) that will remain in order no matter what is inserted. It's for a contact manager project I am working on. I've been experimenting, with the example below.

import java.util.*;

public class TestDriver{

    public static void main(String[] args)
    {
        FullName person1 = new FullName("Stephen", "Harper");
        FullName person2 = new FullName("Jason", "Kenney");
        FullName person3 = new FullName("Peter", "MacKay");
        FullName person4 = new FullName("Rona", "Ambrose");
        FullName person5 = new FullName("Rona", "Aabrose");


        HashSet<FullName> names = new HashSet<FullName>();

        names.add(person3);
        names.add(person1);
        names.add(person4);
        names.add(person2);

        System.out.println(names);      
   } 
}

我希望输出按字母顺序排列名称 - 至少根据他们的名字或姓氏。但是,我甚至无法辨别HashSet用于提出此排序的方法;

I expected the output to put the names in alphabetical order - at least according to either their first or last name. However, I can't even discern the method HashSet used to come up with this ordering;

[Jason Kenney, Rona Ambrose, Stephen Harper, Peter MacKay]

我的问题是,如何告诉我的程序如何对名称进行排序根据我的规格?

My question is, how do I tell my program how to sort the names based on my specifications?

推荐答案

HashSet没有为条目提供任何有意义的顺序。 文档说:

HashSet does not provide any meaningful order to the entries. The documentation says:


它不保证集合的迭代顺序;在
特别是,它不保证订单将随着时间的推移保持不变

It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

获得明智的排序,你需要使用不同的Set实现,如 TreeSet ConcurrentSkipListSet SortedSet 界面的这些实现可让您提供比较者,指定如何订购参赛作品;类似于:

To get a sensible ordering, you need to use a different Set implementation such as TreeSet or ConcurrentSkipListSet. These implementations of the SortedSet interface let you provide a Comparator that specifies how to order the entries; something like:

public class SortByLastName implements Comparator<FullName>{
    public int compare(FullName n1, FullName n2) {
        return n1.getLastName().compareTo(n2.getLastName());
    }
}

TreeSet<FullName> names = new TreeSet<FullName>(new SortByLastName());

您可以改为使FullName类实现可比较的界面,但如果您希望有时按姓氏排序,有时可能首先排序,这可能无益名称或其他标准。

You could instead make the FullName class implement the Comparable interface, but this might be unhelpful if you wanted to sometimes sort by last name, sometimes by first name, or other criteria.

这篇关于告诉HashSet如何对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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