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
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.