订购一个hashset示例? [英] ordering a hashset example?

查看:111
本文介绍了订购一个hashset示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个关于如何在 HashSet 上使用类似类来获取升序的示例。假设我有一个 HashSet 就像这样:

I need an example on how to use a comparable class on a HashSet to get an ascending order. Let’s say I have a HashSet like this one:

HashSet<String> hs = new HashSet<String>();

我怎样才能获得 hs 升序?

推荐答案

使用 TreeSet 。它有一个构造函数采用比较器 。它会自动对 Set 进行排序。

如果要转换 HashSet TreeSet ,然后这样做:

If you want to convert a HashSet to a TreeSet, then do so:

Set<YourObject> hashSet = getItSomehow();
Set<YourObject> treeSet = new TreeSet<YourObject>(new YourComparator());
treeSet.addAll(hashSet);
// Now it's sorted based on the logic as implemented in YourComparator.

如果您拥有的项目已经实现 可比较 及其默认订购单已经是你想要的,那么你基本上不需要提供比较器。然后,您可以直接根据 HashSet 构造 TreeSet 。例如,

If the items you have itself already implements Comparable and its default ordering order is already what you want, then you basically don't need to supply a Comparator. You could then construct the TreeSet directly based on the HashSet. E.g.

Set<String> hashSet = getItSomehow();
Set<String> treeSet = new TreeSet<String>(hashSet);
// Now it's sorted based on the logic as implemented in String#compareTo().



参见:




  • 对象订购教程

  • 收藏教程 - 设置实施

  • See also:

    • Object ordering tutorial
    • Collections tutorial - Set Implementations
    • 这篇关于订购一个hashset示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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