我正在尝试创建一个HashSet(或任何集合类型 - 但我认为HashSet最适合我),无论插入什么,它都将保持有序.这是我正在进行的联系经理项目.我一直在试验,下面的例子.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望输出按字母顺序排列名称 - 至少根据它们的名字或姓氏.但是,我甚至无法辨别HashSet用于提出此排序的方法;
[Jason Kenney, Rona Ambrose, Stephen Harper, Peter MacKay]
Run Code Online (Sandbox Code Playgroud)
我的问题是,如何根据我的规范告诉我的程序如何对名称进行排序?
DNA*_*DNA 18
HashSet不为条目提供任何有意义的顺序.该文件说:
它不能保证集合的迭代顺序; 特别是,它不保证订单会随着时间的推移保持不变.
要获得合理的排序,您需要使用不同的Set实现,例如TreeSet或ConcurrentSkipListSet.SortedSet接口的这些实现允许您提供指定如何对条目进行排序的Comparator ; 就像是:
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());
Run Code Online (Sandbox Code Playgroud)
您可以改为使FullName类实现Comparable接口,但如果您希望有时按姓氏排序,有时按名字或其他条件排序,则可能无效.
Per*_*ror 10
使用Treeset了自然排序.
HashSet--- not ordered/sorted
LinkedhashSet--- maintains insertion order
TreeSet--- sorts in natural order
Run Code Online (Sandbox Code Playgroud)
对于您的情况,请使用TreeSet.
HashSet不保留顺序,去寻找TreeSet并实现自己Comparator的指示TreeSet如何比较
new TreeSet<FullName>(new Comparator<FullName>(){
public int compare(Fullname one, FullName two{/*logic*/}
});
Run Code Online (Sandbox Code Playgroud)
看到
| 归档时间: |
|
| 查看次数: |
34333 次 |
| 最近记录: |