哈希集排序问题

Hashset ordering issue

最近我遇到了这个

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 不保留任何顺序,那么这些数字是如何按升序排列的?

巧合。正好Character的hashCode是它的数值。如果您不断添加的字符多于 HashSet 中哈希桶的数量,您会发现它们乱序了。

HashSet 在内部使用 HashMap

HashMap 使用每个对象的 hashCode() 方法将其元素存储在散列 table 中。

对于字符class,hashcode是它对应的int值。

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

对于 intdouble 数据类型,这些是 auto-boxed into the Integer and Double classes. When you make a HashSet of ints, it uses Integer's hashCode() 方法,这只是 returns int。因此,如果您添加 ints,它们将按排序顺序存储。

但对于 doubleDouble's hashCode() 方法要复杂得多,因为双精度数在内存中的表示方式。

但是,随着时间的推移,当元素超过存储桶大小时,您会发现它不会保持秩序。