First of all, I want to make it clear that I would never use a HashMap to do things that require some kind of order in the data structure and that this question is motivated by my curiosity about the inner details of Java HashMap implementation.
You can read in the java documentation on Object
about the Object
method hashCode
.
I understand from there that hashCode
implementation for classes such as String
and basic types wrappers (Integer
, Long
,...) is predictable once the value contained by the object is given. An example of that would be that calls to hashCode
for any String
object containing the value hello
should return always: 99162322
Having an algorithm that always insert into an empty Java HashMap where String
s are used as keys the same values in the same order. Then, the order of its elements at the end should be always the same, am I wrong?
Since the hash code for a concrete value is always the same, if there are not collisions the order should be the same. On the other hand, if there are collisions, I think (I don't know the facts) that the collisions resolutions should result in the same order for exactly the same input elements.
So, isn't it right that two HashMap objects with the same elements, inserted in the same order should be traversed (by an iterator) giving the same elements sequence?