HashSet order and difference with JDK 7 / 8

前端 未结 4 1537
悲&欢浪女
悲&欢浪女 2021-01-13 18:30

This is a two part question:

  1. Does HashSet implement some hidden ordering mechanic or it just, to quote the documentation:It makes no guarantees as to the
4条回答
  •  心在旅途
    2021-01-13 18:50

    The internal storage of a HashSet is defined by an algorithm. It is not randomized.

    The specification (API) does not specify any particular algorithm, other than it being hash-based. The implementation can choose any algorithm it wants, and is free to choose a different one in future versions.

    However, being algorithm-based, it means that for any particular version of the implementation (Oracle vs IBM, 7 vs 8, ...), adding a particular set of values will always produce the same result, i.e. ordering.

    The ordering is consistent for a specific version, but it is undefined and subject to change without notice in future versions and/or different implementations, so you should never rely on order.

提交回复
热议问题