Thinker
Thinker

Reputation: 6892

What is meant by number of buckets in the HashMap?

I was reading about Hashmap.

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table.

If there are 10 key value pairs in the Hashmap. Assume there Hashcode is different.

Each will resides in one bucket right? Or one bucket can have bucket multiple key-value pairs?

Since bucket in english means a big thing where many objects can reside.

Upvotes: 17

Views: 29885

Answers (3)

Balazs Varhegyi
Balazs Varhegyi

Reputation: 1041

In java if you store an object in HashMap first HashMap implementation calls the hashCode() method to find a bucket location. Then it stores both: the key and value as an Entry. NB! it stores the key also because it's crucial during retrieving the object. Two object can have the same hashcode so if this happens then HashMap will use the same bucket location and store the second object there too. Inside it uses a LinkedList for this. (not java.util.LinkedList, but a simpler implementation)

During retrieving: you have a key -> hashCode() -> bucket location -> search in LinkedList by key -> returning object.

EDIT: So you have one bucket on the same location but a bucket is a LinkedList so it can store multiple Entries. So the number of buckets is the capacity of Hashmap and describes how many Entries you can store without linking them in a list.

You can find a great article and more detailed explanation here: http://javahungry.blogspot.com/2013/08/hashing-how-hash-map-works-in-java-or.html http://javarevisited.blogspot.com/2011/02/how-hashmap-works-in-java.html

Upvotes: 5

vikingsteve
vikingsteve

Reputation: 40378

Yes, exactly, each bucket can have multiple key-value pairs.

The object's hashCode() determines which bucket it goes into, via this expression: object.hashCode() % n, where n = the total number of buckets and % is the modulus operator.

Most often the objects will be well distributed across buckets, but you have no guarantee where they go. This depends on the data and the hashCode function.

Obviously, when the hashCode implementation is poor, the performance of the hashmap will go down.

Also read up on the equals / hashcode contract, which is relevant.

Upvotes: 16

Narendra Pathai
Narendra Pathai

Reputation: 41935

Bucket with hashcode 1    Bucket with hashcode 2 and similar
  K and V                    K and V
  K and V                    K and V 

So the hashCode() of the key decides in which bucket the K V pair goes and the same hashCode is used to find the K V pair while lookup.

hashCode() should never return a constant value. As that would mean that all the objects will be in a single bucket. And that would be same as not using a Map in the first place. As all the key value pairs would be in same bucket, Java will have to iterate through all the objects to find the key.

Upvotes: 3

Related Questions