Is HashMap internally implemented in Java using LinkedList or Array?

dexterousashish picture dexterousashish · Sep 24, 2013 · Viewed 22.7k times · Source

How is HashMap internally implemented? I read somewhere that it uses LinkedList while other places it mentions Arrays.

I tried studying the code for HashSet and found Entry array. Then where is LinkedList used?

Answer

Bernhard Barker picture Bernhard Barker · Sep 24, 2013

It basically looks like this:

 this is the main array
   ↓
[Entry] → Entry → Entry      ← here is the linked-list
[Entry]
[Entry] → Entry
[Entry]
[null ]
[null ]

So you have the main array where each index corresponds to some hash value (mod'ed* to the size of the array).

Then each of them will point to the next entry with the same hash value (again mod'ed*). This is where the linked-list comes in.

*: As a technical note, it's first hashed with a different function before being mod'ed, but, as a basic implementation, just modding will work.