What is bucket in Hashtable or HashMap ?
Ans:Internally , in HashMap the objects are stored as array of Entry objects. Bucket is a collection of Entry objects which has same hashcode value.So a bucket may contain one or more objects with similar hashcode values.
Map mp=new HashMap();
mp.put("Fruit 1","Apple");
mp.put("Fruit 2","Mango");
mp.put("Fruit 3","Banana");
Look at diagram below, here each index of the array (index 0,1,2.....) called as buckets because it may contain one or more objects which has same hashcode value.

In HashMap, key of the object is used to calculate the hashcode using a hashfunction. Now, this hashcode will be used to get the index where the element will be stored.If two or more objects has the same hashcode value then there will be a collision. So to avoid the collision, the objects with the same hashcode value is stored as linked list at a particular index ( e.g Fruit1, Fruit2, Fruit3 three different objects having same hashcode stored at index 0 as LinkedList and Fruit 4 having different hashcode stored at different index ). Here, each index of array (index 0,1,2 ..... etc ) is called as a bucket.
You may also like:
No comments:
Post a Comment