哈希集订购问题[重复]

问题描述 投票:-4回答:2

这个问题在这里已有答案:

最近我遇到了这个

String s = "9495963";
Set<Character> set = new HashSet<Character>();
for(char e : s.toCharArray()){
  set.add(e);
}
System.out.println(set);//[3, 4, 5, 6, 9]

我得到的输出是[3,4,5,6,9],所以,如果HashSet不保留任何顺序,那么为什么这些数字按升序排列?

java hashset treeset
2个回答
7
投票

巧合。恰好,Character的hashCode就是它的数值。如果你继续添加比HashSet中的哈希桶更多的字符,你会发现它们出了故障。


2
投票

HashSet内部使用HashMap

HashMap使用每个Object的hashCode()方法将其元素存储在哈希表中。

对于Character类,hashcode是相应的int值。

public static int hashCode(char value) {
    return (int)value;
}

对于intdouble数据类型,这些是auto-boxed进入IntegerDouble类。当你制作HashSetint时,它使用Integer's hashCode()方法,它只返回int。因此,如果添加ints,它们将按排序顺序存储。

但是对于double来说,Double's hashCode()方法要复杂得多,因为在记忆中表示双打的方式。

但是,随着时间的推移,当元素超过桶大小时,您将看到它不会维持顺序。

© www.soinside.com 2019 - 2024. All rights reserved.