HashSet order and difference with JDK 7 / 8

前端 未结 4 1571
悲&欢浪女
悲&欢浪女 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条回答
  •  萌比男神i
    2021-01-13 18:58

    According to the update on collections changes page

    The alternative String hash function added in 7u6 has been removed from JDK 8, along with the jdk.map.althashing.threshold system property. Instead, hash bins containing a large number of colliding keys improve performance by storing their entries in a balanced tree instead of a linked list. This JDK 8 change applies only to HashMap, LinkedHashMap, and ConcurrentHashMap.

    In rare situations, this change could introduce a change to the iteration order of HashMap and HashSet. A particular iteration order is not specified for HashMap objects - any code that depends on iteration order should be fixed.


    So, Basically

    The Algorithm for hashing your set has changed to improve performance. It changed to a balanced tree instead of a linked list.

    This kind of change might change the iteration order of your set, and it's established that this kind of behavior should be fixed by you, if you depend upon it.

    You're seeing a better implementation of your set, which might look like it's ordered, but it's pure coincidence.

    I would recommend you to not rely on the iteration order for sets, as the order is not a guarantee.

    @Edit

    Another concept is also important, as stated by user Holger,

    The “alternative String hash function” of Java 7 was not used by default. Further, the balanced tree only applies to bucket collision scenarios. Still, as a consequence of this improvement, another, unmentioned change has been made. The mapping of an object’s hashcode to an array position undergoes a transformation which has been simplified from Java 7 to Java 8

提交回复
热议问题