Iteration order of HashSet

后端 未结 9 924
眼角桃花
眼角桃花 2020-11-27 07:32

If every object added to a java.util.HashSet implements Object.equals() and Object.hashCode() in a deterministic fashion, is the iteration order over the HashSet guaranteed

9条回答
  •  借酒劲吻你
    2020-11-27 08:14

    There is no "official" guarantee for anything like this. I would say it is most probably true for instances of the same HashSet implementation, initialized the same way. But I have seen cases for the iteration order being different between Java 5 and 6, for example.

    Also, it may be different for instances of the same HashSet implementation, initialized with different size, due to rehashing. I.e. if you have 100 elements and two sets, one initialized with a size greater than 100, the other with a much smaller size, the second one will get reallocated and its elements rehashed several times while filling up. This may result in elements mapped to the same bucket being added (and thus iterated over) in different order.

    In Java4 and later, you have LinkedHashSet which guarantees that the iteration order will be the order in which its elements were inserted.

提交回复
热议问题