简体   繁体   English

为什么HashSet中的元素顺序是随机的?

[英]Why are elements in HashSet in random order?

I am wondering how does the place of the element in a HashSet is determined.我想知道如何确定 HashSet 中元素的位置。 Is it through some built-in hash function?是通过一些内置的哈希函数吗?

Set <String>set=new HashSet<String>();
    set.add("January");
    set.add("February");
    set.add("July");
    set.add("August");
    set.add("September");
    set.add("October");
    set.add("Novermber");
    set.add("December");
    set.add("March");
    set.add("April");
    set.add("May");
    set.add("June");


    Iterator <String>it=set.iterator();
    while(it.hasNext()){
        System.out.println(it.next());
    }

I get this result我得到这个结果

June
October
December
September
May
March
Novermber
July
January
February
April
August

What is the explanation for this order or the output?这个命令或输出的解释是什么?

HashSet is based on array. HashSet 基于数组。 Item index in array is calculated based on hashCode() function.数组中的项目索引是基于hashCode()函数计算的。

Iterator in HashSet moves over array elements, skipping null elements. HashSet 中的迭代器在数组元素上移动,跳过空元素。 That's why your order is 'strange'.这就是为什么您的订单是“奇怪的”。 If you need to preserve insertion order, use LinkedHashSet .如果您需要保留插入顺序,请使用LinkedHashSet

You have to pay for ordering (in most cases in form of computational time).您必须为订购付费(在大多数情况下以计算时间的形式)。 And the documentation states explicitly, that " [...]. 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. "并且文档明确指出,“ [...]。它不保证集合的迭代顺序;特别是,它不保证顺序会随着时间的推移保持不变。

Therefore I think the order is disregarded for the sake of performance.因此,我认为为了性能而忽略了该顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM