Is the order of values retrieved from a HashMap the insertion order

前端 未结 6 2007
天命终不由人
天命终不由人 2020-11-22 07:26

I am trying figure out the order in which the values in a HashMap are/can be retrieved. Heres the code snippet for the same.

import java.util.HashMap;

publ         


        
6条回答
  •  旧巷少年郎
    2020-11-22 08:28

    The values are printed in the order in which they have been inserted. Is this true in general? I was expecting the values to be printed in random order.

    The HashMap API does not define the order of iteration.

    However, if you look at the implementation of HashMap, you can deduce that there is a complex transient relationship between the iteration order, the keys' hash values, the order in which the keys were inserted and the size of the hashtable. This relationship gets scrambled if the hashtable resizes itself.

    In your case, you are using Integer keys which means that the hash values of the keys are the key values themselves. Also, you inserted the entries in key order. This leads (fortuitously!) to the iteration order matching the insertion order. But if you kept inserting more keys, you would find that the iteration order "wraps around". Then as the table goes through a series of resizes, the order will get progressively more and more scrambled.

    In short, what you are seeing is an artefact of the hashtable implementation, and not something that you can (or should) sensibly make use of. Not least because it could change from one Java release to the next.

提交回复
热议问题