gpt4 book ai didi

java - 订购哈希集示例?

转载 作者:IT老高 更新时间:2023-10-28 20:49:32 25 4
gpt4 key购买 nike

我需要一个示例,说明如何在 HashSet 上使用可比较的类来获得升序。假设我有一个像这样的 HashSet:

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

如何让 hs 按升序排列?

最佳答案

使用 TreeSet反而。它有一个 constructor taking a Comparator .它会自动对Set进行排序。

如果要将 HashSet 转换为 TreeSet,请执行以下操作:

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.

如果您拥有的项目本身已经实现 Comparable并且它的默认排序顺序已经是你想要的了,那么你基本上不需要提供Comparator。然后,您可以直接基于 HashSet 构造 TreeSet。例如

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

另见:

关于java - 订购哈希集示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3380312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com