Friday, May 20, 2016

Hashmap bucket concept with Hashcode and equals method implementation

Bucket concept of HashMap
please look how the bucket id is calculated for a particular key ------------
Hashtable: obj.hashCode() % Hashtable.length
where
legth==capacity for the hashtable or Hashmap or no of bucket
Default no of buckets or capacity for Hashmap is == 16 with 0.75 load factor
load factor 0.75 means on 13th insert again it will grows the buckets with specified capacity


Hashcode and equals Contract example with two different map object having same hashcode for same keys and same values for both the Maps 

public class Test {
    public static void main(String[] args) {

        Map map = new HashMap();
        map.put(1, 11);
        map.put(4, 11);
        System.out.println(map.hashCode());
        Map map1 = new HashMap();
        map1.put(1, 11);
        map1.put(4, 11);
        System.out.println(map1.hashCode());
        if (map.equals(map1)) {
            System.out.println("equal ");
        }
    }
}


click for more details for bucket ID

No comments:

Post a Comment