小编Sim*_*ols的帖子

为什么 HashSet 对单个字母字符进行排序?

所以我知道 HashSet 没有像 SortedSet 这样的真正的排序功能,但是我偶然发现了这一点:

当我运行以下代码时:

 public static void main(String[] args) {
    Set<String> collection = new HashSet<String>(2000);
    String[] data = {"a", "c", "g", "f", "b", "f", "b", "d","q","r","d","m"};
    for(String input: data)
    {
        collection.add(input);
    }
    System.out.println("Output: " + collection);
}
Run Code Online (Sandbox Code Playgroud)

我得到以下输出: 输出:[a, b, c, d, f, g, m, q, r]

这是按字母顺序排序的。这是为什么?由于 HashSet 不是有序集。

所以我尝试使用一串字符而不是单个字符:

public static void main(String[] args) {
    Set<String> collection = new HashSet<String>(2000);
    String[] data = {"atjre", "crj", "gertj", "fertj", "berj"};
    for(String input: data)
    {
        collection.add(input);
    }
    System.out.println("Output: " …
Run Code Online (Sandbox Code Playgroud)

java set hashset

5
推荐指数
1
解决办法
1465
查看次数

标签 统计

hashset ×1

java ×1

set ×1