Why the order of elements in HashSet's keySet changes from run to run?

后端 未结 3 1031
抹茶落季
抹茶落季 2021-01-13 04:42

I have some code utilizing standard Java collections: arrays, ArrayDeques, HashMaps, Lists, HashSets. My code is expected to be deterministic: the hash codes of all the elem

相关标签:
3条回答
  • 2021-01-13 04:58

    If you need a stable ordered HashSet, then you should be using LinkedHashSet per the javadoc,

    Hash table and linked list implementation of the Set interface, with predictable iteration order

    And per the HashSet javadoc,

    ... makes no guarantees as to the iteration order of the set

    0 讨论(0)
  • 2021-01-13 05:13

    Just copying here what is already included in the question. A quick look through the sources showed that in 1.7, HashMap indeed has non-deterministic behavior, and each instance seeds the hashes of the elements with some random value. In 1.8, the implementation was changed, and the randomization doesn't seem to be there any more.

    0 讨论(0)
  • 2021-01-13 05:18

    From the documentation of HashSet:

    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.

    0 讨论(0)
提交回复
热议问题