这个HashSet如何产生排序输出? [英] How is this HashSet producing sorted output?

查看:647
本文介绍了这个HashSet如何产生排序输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码生成输出 [1,2] ,即使hashset未排序。

The following code produces the out put [1,2]even though hashset is not sorted.

Set set = new HashSet();
set.add(new Integer(2));
set.add(new Integer(1));
System.out.println(set);

为什么会这样?

推荐答案

此行为是由以下几个原因造成的:

This behaviour is caused by several separate reasons:


  • 整数哈希自己

  • 在Java中, HashMap s和 HashSet 由数组备份

  • 他们还使用较高位修改哈希值来修改低位;如果散列在0..15的范围内,则不会被修改

  • 对象的内容取决于修改散列的低位

  • 当迭代地图或集合时,内部表将按顺序扫描

  • Integers hash to themselves
  • in Java, HashMaps and HashSets are backed up by an array
  • they also modify hashes using the higher bits to modify the lower bits; if the hash is in range 0..15, it's therefore not modified
  • what bucket an object goes depends on the lower bits of the modified hash
  • when iterating over a map or a set, the inner table is scanned sequentially

因此,如果添加几个小(<16)对hashmap / hashset的整数,会发生这种情况:

So if you add several small (<16) integers to a hashmap/hashset, this is what happens:


  • 整数 i 有hashcode i

  • 因为它小于16,所以修改后的散列也是 i

  • 它落在桶中。 i

  • 在迭代时,会按顺序访问存储桶,因此如果存储的所有数据都是小整数,则会以升序检索它们订单

  • integer i has hashcode i
  • since it's less than 16, it's modified hash is also i
  • it lands in the bucket no. i
  • when iterating, the buckets are visited sequentially, so if all you stored there are small integers, they will be retrieved in ascending order

请注意,如果存储桶的初始数量太小,整数可能会落在以后编号的存储桶中:

Note that if the initial number of buckets is too small, the integers may land in buckets not numbered after them:

HashSet<Integer> set = new HashSet<>(4);
set.add(5); set.add(3); set.add(1);
for(int i : set) {
  System.out.print(i);
}

打印 153

这篇关于这个HashSet如何产生排序输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆