Iteration order of HashSet

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

    As per the javadoc:

    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 iterators returned by this class's iterator method are fail-fast: if the set is modified at any time after the iterator is created

    And the method iterator:

    Returns an iterator over the elements in this set. The elements are returned in no particular order.

    So I don't think you can make such an assumption.

提交回复
热议问题