Iteration order of HashSet

后端 未结 9 858
眼角桃花
眼角桃花 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:15

    Such assumption cannot be made. The javadoc says that:

    This class implements the Set interface, backed by a hash table (actually a HashMap instance). 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.

    The closest you can get is to use a LinkedHashSet, which maintains the insertion order.

    0 讨论(0)
  • 2020-11-27 08:17

    I am sure that the Java developers want you to assume the answer is "no". In particular, for hash tables, why would they make it slower for everyone else who doesn't need this property to guarantee that objects whose hashes clash (identical hashCode % size) are observed in the same order regardless of the order in which they were put in?

    0 讨论(0)
  • 2020-11-27 08:19

    Wanted to confirm / upvote earlier comments. In short, Do Not Rely on HashSet iteration in consistent order. This can and will introduce bugs in your system.

    We just found and fixed a bug where the iteration order was inconsistent in HashSet even with:

    • Identical insertion order.
    • Objects of a class with a valid equals() and hashCode() method.

    And fixed it by using LinkedHashSet.

    Thanks to the earlier posters :)

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