In a hashmap, how is the hashcode lookup a constant O(1)
?
We know that internally a hashmap creates an array to hold a hash-code for a given key-value. With the use of hashing function, hashmap generates hash code. We also know that for lookup, the hashmap takes constant time (assuming there is no collision). Whenever we request a hashmap to look for a value for a given key it first calculates the bucket location (i.e index of the array which is mapped with hashcode of the given key). Then it fetches the value. I understand the second part will take constant time. But what about the first part? How is the lookup of the array index for hashcode constant? Especially when a hashmap has millions of values?
My StackOverflow search found multiple question on hashmap, but mostly they answered the second part of my question and not for the first part.
Few of the links I found:
I also found this question posted by a user at javarevisited.blogspot:
Hi Javin, Need a clarification on one of my recent interview question. For search and sort which Collection datastructure to prefer : ArrayList or LinkedList. I mentioned ArrayList would be the choice for retrieval operations as it implements Random Access whereas Linked list would be a better choice for insertion / deletion as it holds pointers for before and after node. My followup question, so do you mean to say retrieval is faster using an Arraylist which holds 1million records ? I said if index is known we can use the contains() and get the value. But clarify me on this 1million scenario in real dynamic case i.e. without knowing index. Would ArrayList be still faster ?