gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 02:36:17 25 4
gpt4 key购买 nike

所以我所知道的是 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);
}

我得到以下输出: 输出:[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: " + collection);
}

我得到以下输出:输出:[crj, atjre, fertj, gertj, berj]

现在他们不再排序了,有什么解释吗?或者这只是一个偶然的巧合?

最佳答案

HashSet 实现了Set 接口(interface)。这意味着不能保证元素的顺序。

This class implements the Set interface, backed by a hash table (actually a HashMap instance). 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. Source

添加、删除几次后,您会看到差异。

但是,“不保证顺序”并不意味着“保证随机顺序”。你的问题的确切答案是,

The hashcode-method of the String class also comes into play here, for single character Strings the hashcode will just be the int value of the one char in the String. And since char's int values are ordered alphabetically, so will the computed hashes of single char Strings.

关于java - 为什么 HashSet 对单个字母字符进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50800499/

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