Values are printed in the order in which they were inserted. Is this true in general? I expected the values to be printed in random order.
The HashMap
API does not define iteration order.
However, if you look at the implementation of HashMap, you can determine that there is a complex transitional relationship between the iteration order, key hash values, the order in which the keys were inserted, and the size of the hash table. This link gets scrambled if the hash table is resized.
In your case, you use the Integer
keys, which means that the key hash values are the key values themselves. In addition, you inserted records in order of priority. This leads (randomly) to an iteration order corresponding to the input order. But if you continue to insert more keys, you will find that the iteration order is “wrapped”. Then, when the table goes through a series of changes, the order will become more and more scrambled.
In short, what you see is an artifact of the hash table implementation, and not something that you can (or should) reasonably use. Not least because it can change from one version of Java to the next.
Stephen C Jan 27 '10 at 5:48 2010-01-27 05:48
source share